2011-03-20 91 views
2

當我設置一個工具提示綁定在WPF自定義控件,這樣它完美的作品:WPF自定義控件的工具提示MultiBinding問題

public override void OnApplyTemplate() 
{ 
    base.OnApplyTemplate(); 
    ... 
    SetBinding(ToolTipProperty, new Binding 
         { 
          Source = this, 
          Path = new PropertyPath("Property1"), 
          StringFormat = "ValueOfProp1: {0}" 
         });   
} 

但是當我嘗試使用MultiBinding在工具提示有幾個特性,不起作用:

public override void OnApplyTemplate() 
{ 
    base.OnApplyTemplate(); 
    ... 
    MultiBinding multiBinding = new MultiBinding(); 
    multiBinding.StringFormat = "ValueOfProp1: {0}\nValueOfProp2: {1}\nValueOfProp3: {2}\n"; 

     multiBinding.Bindings.Add(new Binding 
     { 
      Source = this, 
      Path = new PropertyPath("Property1") 
     }); 
     multiBinding.Bindings.Add(new Binding 
     { 
      Source = this, 
      Path = new PropertyPath("Property2") 
     }); 
     multiBinding.Bindings.Add(new Binding 
     { 
      Source = this, 
      Path = new PropertyPath("Property3") 
     }); 

     this.SetBinding(ToolTipProperty, multiBinding);   
} 

在這種情況下,我根本沒有顯示工具提示。

我在哪裏錯了?

回答

3

事實證明,StringFormatMultiBinding僅適用於string類型的屬性,而ToolTip屬性爲object型。在這種情況下,MultiBinding需要定義一個值轉換器。

作爲一種變通方法,你可以設置一個TextBlockToolTip和綁定使用MultiBindingText財產(因爲Textstring型的,它會與StringFormat工作):

TextBlock toolTipText = new TextBlock(); 

MultiBinding multiBinding = new MultiBinding(); 
multiBinding.StringFormat = "ValueOfProp1: {0}\nValueOfProp2: {1}\nValueOfProp3: {2}\n"; 

multiBinding.Bindings.Add(new Binding 
{ 
    Source = this, 
    Path = new PropertyPath("Property1") 
}); 
multiBinding.Bindings.Add(new Binding 
{ 
    Source = this, 
    Path = new PropertyPath("Property2") 
}); 
multiBinding.Bindings.Add(new Binding 
{ 
    Source = this, 
    Path = new PropertyPath("Property3") 
}); 

toolTipText.SetBinding(TextBlock.TextProperty, multiBinding); 

ToolTip = toolTipText; 
+0

謝謝你,它像一個魅力! +1我稍後會接受你的回答,以便讓你獲得更多的代表點。再次感謝! – rem 2011-03-20 21:55:28

+0

@rem - 不客氣!我認爲你已經可以接受了:) – 2011-03-21 20:52:44