如何为每个 StackPanel 项目设置单独的工具提示?

How can I set individual ToolTips for each StackPanel item?

我对 WPF 比较陌生,正在使用 Stackpanel 显示图像列表。此图像列表是动态的,因此 Stackpanel 项目是在 运行 时在代码中添加的,而不是直接在 XAML.

中添加的

当时我很好奇如何为 Stackpanel 中的每个图像显示单独的工具提示。我在想我可以做如下事情:

private void mainTaskBar_PreviewMouseMove(object sender, MouseEventArgs e)
{
    foreach (Image img in imgList)
        if (img == e.OriginalSource)
            displayCorrespondingTooltip(img);
}

但这似乎有点过分了。有什么方法可以简单地获取堆栈面板中的子项列表,并简单地使用 SetToolTip() 设置每个单独的工具提示?我觉得这样会优雅很多。

谢谢!

您可以定义如下方法来为各种控件分配工具提示:

public void displayCorrespondingTooltip<T>(T control, string tooltipText)
    {
       //For images
        if (control.GetType() == typeof(Image))
        {
            (control as Image).ToolTip = tooltipText;
        }
       //For Rectangles
        if (control.GetType() == typeof(Rectangle))
        {
            (control as Rectangle).ToolTip = tooltipText;
        }
    }

这辆面包车的名字如下:

displayCorrespondingTooltip<Image>(img, "This will be the image tooltip");
displayCorrespondingTooltip<Rectangle>(rectObject,"rectangle tooltip");