【问题标题】:ToolTip of a WPF Custom Control with Custom Control's property value具有自定义控件属性值的 WPF 自定义控件的工具提示
【发布时间】:2011-03-21 04:03:09
【问题描述】:

在 WPF 应用程序中,我有一个自定义控件。

public class MyControl : Control
{
    static MyControl()
    {
        DefaultStyleKeyProperty.OverrideMetadata(typeof(MyControl), new FrameworkPropertyMetadata(typeof(MyControl)));
    }

    public static readonly DependencyProperty ControlStatusProperty = DependencyProperty.Register("ControlStatus", typeof(int), typeof(MyControl), new PropertyMetadata(16));

    public int ControlStatus
    {
        get
        {
            return (int)GetValue(ControlStatusProperty);
        }
        set
        {
            SetValue(ControlStatusProperty, value);
            ChangeVisualState(false);
        }
    }
 ...
    public override void OnApplyTemplate()
    {
        base.OnApplyTemplate();
       ...
        ToolTipService.SetToolTip(this, "Status: " + ControlStatus);          
    }

    private void ChangeVisualState(bool useTransitions)
    {
       ...
       ToolTipService.SetToolTip(this, "Status: " + ControlStatus);
    }

问题是:ToolTip 总是显示ControlStatus 属性的值,该值在OnApplyTemplate() 方法执行时已经存在。
自定义控件的ControlStatus 属性在运行时已更改,但工具提示仍始终显示初始值。

如何让自定义控件的工具提示始终显示自定义控件属性的当前值?

【问题讨论】:

    标签: c# wpf silverlight custom-controls tooltip


    【解决方案1】:

    您需要使用绑定而不是使用ToolTipService.SetToolTip 静态设置工具提示。你的情况应该是这样的:

    SetBinding(ToolTipProperty, new Binding
                                {
                                    Source = this,
                                    Path = new PropertyPath("ControlStatus"),
                                    StringFormat = "Status: {0}"
                                });
    

    【讨论】:

    • 是的!效果很好! +1 请您帮助理解:如何设置具有多个属性的工具提示。比如:"Property1Value: " + Property1 + "\n" + "Property2Value: " + Property2 + "\n"
    • @rem - 在这种情况下,您可以使用MultiBinding 而不仅仅是Binding。在MultiBinding 中,您将StringFormat 设置为“Property1Value: {0}\nProperty2Value: {1}\n”,其Bindings 集合将包含每个属性的Binding 对象。
    • 谢谢,帕夫洛!你的回答真的很有帮助,它完全回答了我原来的问题,所以我接受了。我在实现 MultiBinding 方法时遇到了一些问题,所以我为它打开了一个单独的问题:stackoverflow.com/questions/5371552/…
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-12-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多