WPF自定义控件的ToolTip MultiBinding问题

当我在WPF自定义控件中设置工具提示绑定时,这种方式非常完美:

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

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

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

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

我哪里错了?

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

作为一种解决方法,您可以将TextBlock设置为ToolTip并使用MultiBinding绑定其Text属性(因为Text的类型为string它将与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;