代码之家  ›  专栏  ›  技术社区  ›  Julien Poulin

如何根据WPF中的DataContext数据类型显示不同的工具提示?

  •  0
  • Julien Poulin  · 技术社区  · 15 年前

    我有个摘要 UserControl 我想展示的 ToolTip 在。这个 工具提示 应根据派生UserControls中定义的DataContext的类型不同。

    有什么方法可以定义不同的 工具提示 对于基类中的每种类型?如果没有,如何在派生的用户控件中设置此工具提示?

    以下是我的想法:

    <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>
    
    2 回复  |  直到 6 年前
        1
  •  1
  •   Julien Poulin    6 年前

    无法编写一个自定义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“local”定义为该命名空间和程序集):

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

    并确保用户控件的根Visual绑定其工具提示属性:

    <Grid 
        ToolTip="{Binding Converter={StaticResource toolTipConverter}}"
        Background="Blue">
        <!-- stuff goes here -->
    </Grid>
    
        2
  •  0
  •   Maxim Zabolotskikh    8 年前

    虽然这是一篇很老的文章,但我还是会发表我的答案,因为我今天也面临同样的问题。基本上,我把所有工具提示模板放到资源中,就像问题的作者那样。为了真正做到这一点,工具提示内容和资源部分缺少绑定。有了这些,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>