2009-08-17 56 views
0

我有一个摘要UserControl,我想显示一个ToolTip。此ToolTip应基于在派生的UserControls中定义的DataContext的类型而不同。如何根据Wpf中的DataContext DataType显示不同的工具提示?

是否有一种方法可以为基类中的每种类型定义不同的ToolTip?如果没有,我怎么能在派生的UserControl中设置这个工具提示?

这里是我想我会去:

<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

你不能笔者,返回你想显示该类型的信息自定义ValueConverter?

您可以'喜欢这一点'来让转换器接受您建议的数据模板,但这将完全启用您的方案。

首先,创建值转换器。请原谅我的快速代码:

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

}

然后在你的用户控件的资源实例(我定义的xmlns“本地”是这个命名空间和装配):

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

而且使确保根视觉用户控件的绑定其ToolTip属性:

<Grid 
    ToolTip="{Binding Converter={StaticResource toolTipConverter}}" 
    Background="Blue"> 
    <!-- stuff goes here --> 
</Grid> 
+0

谢谢,我现在通过在代码中创建一个可视化树来使它工作。但我真的希望能够在xaml中定义模板,因为这个应用程序必须进行本地化,这会容易得多。你如何让转换器接受模板?你能指点我一些参考链接吗? – 2009-08-18 07:57:25

+0

我设法做到最后,它完美的工作,谢谢你:-) – 2009-08-18 11:36:49

0

虽然这是一个真正的老帖子,我仍然会发表我的回答,因为我今天面临同样的问题。基本上,我最终将所有的工具提示模板都放到了资源中,就像问题的作者一样。为此,工具提示内容和资源部分缺少绑定。有了这些,temlates确实得到应用。

<UserControl ... 
    <UserControl.ToolTip> 
    <Tooltip Content="{Binding}"> 
     <Tooltip.Resources> 
     <DataTemplate DataType="{x:Type Type1}"> 
      ... 
     </DataTemplate> 
     <DataTemplate DataType="{x:Type Type2}"> 
      ... 
     </DataTemplate> 
     </Tooltip.Resources> 
    </Tooltip> 
</UserControl>