Shane Duffy
Shane Duffy

Reputation: 1147

How can I set individual ToolTips for each StackPanel item?

I'm relatively new to WPF, and am using a Stackpanel to display a list of images. This list of images is dynamic, so the Stackpanel items are added at run-time in code, rather than directly in the XAML.

I was curious then as to how I would manage to display individual tooltips for each image in the Stackpanel. I was thinking I could do something as follows:

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

But this seems a bit excessive to have to do. Is there any way you could simply get a list of the children in the stackpanel and simply set each individual ToolTip with SetToolTip()? I feel like that would be much more elegant.

Thanks!

Upvotes: 2

Views: 411

Answers (1)

sujith karivelil
sujith karivelil

Reputation: 29006

You can define a method like the following to assign tooltip for various controls:

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;
        }
    }

And this van be called like The following:

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

Upvotes: 1

Related Questions