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;