views:

159

answers:

1

I have an abstract UserControl that I want to show a ToolTip on. This ToolTip should be different based on the Type of the DataContext which is defined in the derived UserControls.

Is there a way to define a different ToolTip for each type in the base class? If not, how can I set this ToolTip in the derived UserControl?

Here is how I thought I would go:

<UserControl ...
  <UserControl.ToolTip>
    <DataTemplate DataType="{x:Type Library:Event}">
      <StackPanel>
        <TextBlock FontWeight="Bold" Text="{Binding Name}" />
        <TextBlock>
          <TextBlock.Text>
            <Binding Path="Kp" StringFormat="{}Kp: {0}m" />
          </TextBlock.Text>
        </TextBlock>
      </StackPanel>
    </DataTemplate>
  </UserControl.ToolTip>
</UserControl>
+1  A: 

Couldn't you author a custom ValueConverter that returns the information you'd like to display for the type?

You could 'fancy this up' a bit to allow the converter to accept data templates like you're suggesting, but this will totally enable your scenario.

First, create the value converter. Pardon my quick code:

public class ToolTipConverter : IValueConverter
{
     public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
    UIElement tip = null;

    if (value != null)
    {
        // Value is the data context
        Type t = value.GetType();
        string fancyName = "Unknown (" + t.ToString() + ")";

        // Can use IsInstanceOf, strings, you name it to do this part...
        if (t.ToString().Contains("Person"))
        {
            fancyName = "My custom person type";
        };


        // Could create any visual tree here for the tooltip child
        TextBlock tb = new TextBlock
        {
            Text = fancyName
        };
        tip = tb;
    }

    return tip;
}

public object ConvertBack(object o, Type t, object o2, CultureInfo ci)
{
    return null;
}

}

Then instantiate it in your user control's resources (I defined the xmlns "local" to be this namespace and assembly):

    <UserControl.Resources>
    <local:ToolTipConverter x:Key="toolTipConverter" />
</UserControl.Resources>

And make sure the root visual of your user control binds its ToolTip property:

<Grid 
    ToolTip="{Binding Converter={StaticResource toolTipConverter}}"
    Background="Blue">
    <!-- stuff goes here -->
</Grid>
Jeff Wilcox
Thanks, I made it work for now by creating a visual tree in code. But I'd really like to be able to define the templates in xaml since this application will have to be localized, it will be much easier. How do you allow the Converter to accept a template? Can you point me to some reference links?
Julien Poulin
I managed to do it in the end and it works perfectly, thank you :-)
Julien Poulin