WPF Custom Control's ToolTip MultiBinding problem

谁都会走 提交于 2020-01-02 17:51:32

问题


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

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.

Where am I wrong?


回答1:


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.

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;


来源:https://stackoverflow.com/questions/5371552/wpf-custom-controls-tooltip-multibinding-problem

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!