WPF Custom Control's ToolTip MultiBinding problem
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}\nValu开发者_StackOverflow中文版eOfProp3: {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?
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;
精彩评论