繁体   English   中英

具有自定义控件属性值的WPF自定义控件的工具提示

[英]ToolTip of a WPF Custom Control with Custom Control's property value

在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属性在运行时已更改,但ToolTip仍始终显示初始值。

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

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM