简体   繁体   中英

ToolTip of a WPF Custom Control with Custom Control's property value

In a WPF application I have a Custom Control.

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

The problem is: ToolTip always shows the value of ControlStatus property which had been at the moment of OnApplyTemplate() method execution.
The ControlStatus property of a custom control have been changed during run-time, but the ToolTip still always shows initial value.

How could I make the ToolTip of a Custom Control always show the current value of Custom Control's property?

You need to use binding instead of statically setting the tool tip with ToolTipService.SetToolTip . In your case it should be like this:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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