簡體   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