2011-03-20 67 views
4

在WPF应用程序中,我有一个自定义控件。具有自定义控件属性值的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); 
    } 

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

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

回答

5

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

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

是的!它很棒! +1请您帮助理解:如何设置具有多个属性的工具提示。例如:'“Property1Value:”+ Property1 +“\ n”+“Property2Value:”+ Property2 +“\ n”' – rem 2011-03-20 20:11:42

+0

@rem - 在这种情况下,您可以使用'MultiBinding'而不是'Binding'。在'MultiBinding'中,你将'StringFormat'设置为“Property1Value:{0} \ nProperty2Value:{1} \ n”,它的'Bindings'集合将包含每个属性的'Binding'对象。 – 2011-03-20 20:18:41

+0

谢谢,帕夫洛!你的答案真的很有用,它完全回答了我原来的问题,所以我接受了它。我在实现MultiBinding方法时遇到了一些问题,所以我打开了一个单独的问题:http://stackoverflow.com/questions/5371552/wpf-custom-controls-tooltip-multibinding-problem – rem 2011-03-20 21:22:28