2017-08-23 31 views
0

鑑於我有一個控制從什麼地方叫SomeControl窗口樣式的資源不覆蓋用戶控件屬性時,應當出示

在MyUserControl.xaml我用SomeControl像這樣:

<Grid.Resources> 
<Window.Resources> 
    <Style TargetType="local:SomeControl"> 
    <Setter Property="ToolTip"> 
    <Setter.Value> 
     <ToolTip> 
      <TextBlock Text="FOO"/> 
     </ToolTip> 
    </Setter.Value> 
    </Setter> 
    </Style> 
</Window.Resources> 
</Grid.Resources> 
<Grid> 
    <!-- Others controls in here --> 
    <local:SomeControl /> 
</Grid> 

在Window.xaml:

<Window.Resources> 
    <Style TargetType="local:SomeControl"> 
    <Setter Property="ToolTip"> 
    <Setter.Value> 
     <ToolTip> 
      <TextBlock Text="BAR"/> 
     </ToolTip> 
    </Setter.Value> 
    </Setter> 
    </Style> 
</Window.Resources> 
<Grid> 
    <local:MyUserControl /> 
</Grid> 

結果是當我想讓它顯示Bar時,它會顯示Foo。 如果我從UserControl中刪除工具提示,就會使用Window的樣式,並且它會像我期望的那樣顯示Bar

爲什麼Window樣式不存在時覆蓋UserControl顯式ToolTip屬性,但在刪除時會如何?

爲了記錄,我也嘗試更改MyUserControl以使用名稱相同的x:Key的DynamicResource並且沒有任何影響。

將兩者都更改爲ToolTipService.ToolTip也具有相同的結果。

編輯:我修正了這個例子,說明即使ToolTip沒有在本地級別上設置,它仍然不會覆蓋樣式。

+0

爲什麼您的樣式是針對SomeControl的,但您的控件名爲MyUserControl? – SledgeHammer

+0

因爲用戶控件內部的類型是'SomeControl'。我沒有試圖定位'MyUserControl',我試圖定位'SomeControl'。 'Window'有一個'UserControl',它有一個'SomeControl'工具提示在'SomeControl'上,而不是'UserControl' – user99999991

回答

0

除非有人能夠回答如何重寫子工具提示的風格,否則我最終將ToolTip對象設置爲依賴屬性MyUserControl並將其傳遞給SomeControl

我所做的依賴項屬性被稱爲ExampleToolTip

MyUserControl.xaml:

<UserControl x:Name='MainControl'> 
    <UserControl.Resources> 
    <ToolTip x:Key="DefaultSomeControlToolTip"> 
     <TextBlock Text="FOO"/> 
    <ToolTip> 
    </UserControl.Resources> 
    <Grid> 
    <local:SomeControl ToolTip="{Binding ExampleToolTip, ElementName=MainControl, TargetNullValue={StaticResource DefaultSomeControlToolTip}}"/> 
    </Grid> 
</UserControl> 

Window.xaml:

<Grid> 
    <local:MyUserControl> 
    <local:MyUserControl.ExampleToolTip> 
     <ToolTip> 
      <TextBlock Text="BAR"/> 
     </ToolTip> 
    </local:MyUserControl.ExampleToolTip> 
    </local:MyUserControl> 
</Grid> 

現在我可以用MyUserControl與它的特殊的 「富」 工具提示在SomeControlWindow有其「BAR」工具提示覆蓋它。

+1

據我所知(而且從測試),它不會鑽取可視化樹。它只將它應用於頂層控件,並且如果控件位於像ListBoxItem這樣的容器中,則可以執行您正在嘗試執行的操作。如果您在對話框上粘貼了TextBlock和Button並嘗試將字體權重應用於TextBlock類型,則可以看到此內容。只有實際的TextBlock類型纔會提取它。該按鈕內的TextBlock沒有。 – SledgeHammer