WPF自定义控件的工具提示多绑定问题 [英] WPF Custom Control's ToolTip MultiBinding problem

查看:81
本文介绍了WPF自定义控件的工具提示多绑定问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我在WPF自定义控件中设置ToolTip绑定时,它可以完美工作:

When I set a ToolTip Binding In a WPF Custom Control, this way it works perfect:

public override void OnApplyTemplate()
{
    base.OnApplyTemplate();
   ...
    SetBinding(ToolTipProperty, new Binding
                        {
                            Source = this,
                            Path = new PropertyPath("Property1"),
                            StringFormat = "ValueOfProp1: {0}"
                        });          
}

但是当我尝试使用MultiBinding在ToolTip中具有多个属性时,它不起作用:

But when I try to use MultiBinding to have several properties in the ToolTip, it doesn't work:

public override void OnApplyTemplate()
{
    base.OnApplyTemplate();
   ...
    MultiBinding multiBinding = new MultiBinding();
    multiBinding.StringFormat = "ValueOfProp1: {0}\nValueOfProp2: {1}\nValueOfProp3: {2}\n";

        multiBinding.Bindings.Add(new Binding
        {
            Source = this,
            Path = new PropertyPath("Property1")
        });
        multiBinding.Bindings.Add(new Binding
        {
            Source = this,
            Path = new PropertyPath("Property2")
        });
        multiBinding.Bindings.Add(new Binding
        {
            Source = this,
            Path = new PropertyPath("Property3")
        });

        this.SetBinding(ToolTipProperty, multiBinding);          
}  

在这种情况下,我根本没有显示工具提示。

In this case I have no ToolTip shown at all.

我在哪里错了?

推荐答案

事实证明,上的 StringFormat MultiBinding 仅适用于 string 类型的属性,而 ToolTip 属性的类型为对象。在这种情况下, MultiBinding 需要定义一个值转换器。

It turns out that StringFormat on MultiBinding works only on properties of type string, while the ToolTip property is of type object. In this case the MultiBinding requires a value converter defined.

作为解决方法,您可以将 TextBlock 设置为 ToolTip 并使用 MultiBinding 绑定其<$​​ c $ c> Text 属性(因为 Text 类型为 string ,它将与 StringFormat )一起使用:

As a workaround you could set a TextBlock as a ToolTip and bind its Text property using MultiBinding (since Text is of type string it'll work with StringFormat):

TextBlock toolTipText = new TextBlock();

MultiBinding multiBinding = new MultiBinding();
multiBinding.StringFormat = "ValueOfProp1: {0}\nValueOfProp2: {1}\nValueOfProp3: {2}\n";

multiBinding.Bindings.Add(new Binding
{
    Source = this,
    Path = new PropertyPath("Property1")
});
multiBinding.Bindings.Add(new Binding
{
    Source = this,
    Path = new PropertyPath("Property2")
});
multiBinding.Bindings.Add(new Binding
{
    Source = this,
    Path = new PropertyPath("Property3")
});

toolTipText.SetBinding(TextBlock.TextProperty, multiBinding);

ToolTip = toolTipText;

这篇关于WPF自定义控件的工具提示多绑定问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆