【问题标题】:WPF Custom Control's ToolTip MultiBinding problemWPF自定义控件的ToolTip MultiBinding问题
【发布时间】:2011-03-20 21:16:43
【问题描述】:

当我在 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);          
}  

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

我哪里错了?

【问题讨论】:

    标签: c# wpf silverlight custom-controls tooltip


    【解决方案1】:

    事实证明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;
    

    【讨论】:

    • 谢谢,它就像一个魅力! +1 我稍后会接受你的回答,让你获得更多的代表点。再次感谢!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-10-26
    • 1970-01-01
    • 1970-01-01
    • 2010-12-22
    • 2011-03-09
    • 1970-01-01
    相关资源
    最近更新 更多