2011-12-27 53 views
1

在我的自定義控件中,我想要programmaticaly根據選項啓用或禁用工具提示。這是我的圖標模板如何定義的:ToolTip爲空。我如何訪問它?

<Image x:Name="PART_IconImage" Stretch="None" VerticalAlignment="Top" HorizontalAlignment="Center" Source="{TemplateBinding Icon}" 
            ToolTipService.ToolTip="{TemplateBinding Caption}" /> 

我使用這個代碼訪問工具提示和啓用/禁用:

// Enable tooltip when caption not shown 
      if (this.IconImage != null) 
      { 
       var toolTip = ToolTipService.GetToolTip(this.IconImage) as ToolTip; 

       if (toolTip != null) 
        toolTip.IsEnabled = this.CaptionVisibility.HasValue 
             ? (this.CaptionVisibility.Value == Visibility.Collapsed) 
             : (this.ParentToolbar.CaptionsVisibility == Visibility.Collapsed); 
      } 

GetToolTip返回null。任何想法爲什麼?

P.S.我在這裏遵循這個建議:How to programmatically access ToolTipService of a Silverlight FrameworkElement? 但它不適用於我。

回答

2

你肯定ToolTipService.GetToolTip被返回null,而不是返回ToolTip以外的東西?

我做了一個快速實驗類似於你的代碼,發現ToolTipService.GetToolTip返回的字符串。我當然將ToolTipService.ToolTip綁定到字符串依賴項屬性。我懷疑你也從GetToolTip得到了一個字符串,但是在你調用這個方法之後你添加的as ToolTip會刪除這個字符串。

以編程方式禁用工具提示的一種方法是將其綁定到視圖模型上包含工具提示文本(如果工具提示應顯示)的屬性,如果工具提示不應顯示,則爲null。

或者,你可以使用一個ToolTip,而不是字符串,作爲工具提示爲您的控件。這樣,你應該能夠訪問ToolTip對象,並啓用/在你的代碼上述禁用它:

<Image x:Name="PART_IconImage" Stretch="None" VerticalAlignment="Top" HorizontalAlignment="Center" Source="{TemplateBinding Icon}"> 
    <ToolTipService.ToolTip> 
     <ToolTip> 
      <TextBlock Text="{TemplateBinding Caption}" /> 
     </ToolTip> 
    </ToolTipService.ToolTip> 
</Image> 
+0

你可能會糾正,它返回的字符串。我沒有檢查。我不想束縛,因爲這不是我控制的公共財產。我已經通過完全刪除XAML並編寫代碼在我需要時執行'ToolTipService.SetToolTip'來解決此問題。我會標記你的答案,因爲它會按你的方式工作,而且我已經有了我的答案 – katit 2011-12-27 17:24:50

1

爲什麼不簡單地將下面的屬性綁定到布爾屬性?

ToolTipService.IsEnabled 

然後,每當要禁用/啓用簡單地更改綁定的屬性

< Image ToolTipService.IsEnabled="{Binding Path=SomeProperty}">

也看看How do you disable tooltips in code at runtime

+0

然後看看鏈接我提到它可以幫助你 – 2011-12-27 15:53:10

+0

他有一個點,現在你願意使用綁定而不是MVVM。這是hackish。 – 2011-12-27 15:54:49

+0

我刪除了我以前的所有評論。 Silverlight不會將IsEnabled作爲依賴項屬性公開。即使它 - 我不想公開這樣的屬性在我的控制 – katit 2011-12-27 16:26:58

相關問題