2015-12-26 55 views
0

我想要帶有小圖標作爲內容的按鈕。基於父級樣式屬性的樣式觸發器

的圖標定義並存儲在一個ResourceDictionary這樣的:

<Path x:Key="BackIcon" Data="F1 M 57,42L 57,34L 32.25,34L 42.25,24L 31.75,24L 17... "/> 
<Path x:Key="LoadFromFileIcon" Data="F1 M 48,39L 56,39L 56,49L 63.25,49L 52,60.2... "/> 
<Path x:Key="SaveToFileIcon" Data="F1 M 48,60L 56,60L 56,50L 63.25,50L 52,38.75L... "/> 

因爲我還需要提供Path.FillPath.Stretch等特性,我決定把我自己的IconButtonStyle,所以我不會有重複每Path相同屬性的圖標字典,使按鍵很容易像這樣:

<Button Style="{StaticResource IconButtonStyle}" 
    Content="{StaticResource ResetIcon}"/> 

這是我想出了:

<Style x:Key="IconButtonStyle" TargetType="Button"> 
    <Style.Resources> 
     <Style TargetType="Path"> 
      <Setter Property="Fill" Value="Black"/> <!-- Default path fill. --> 

      <Style.Triggers> 
       <!-- How can I set path fill to "Red" based on the parent Button IsEnabled property? --> 
      </Style.Triggers> 
     </Style> 
    </Style.Resources> 

    <Style.Triggers> 
     <Trigger Property="IsEnabled" Value="false"> 
      <!-- ?? --> 
     </Trigger> 
    </Style.Triggers> 

</Style> 

我的自定義圖標按鈕具有通過Style.Resources定義的默認路徑樣式。設置默認路徑填充很容易,但我無法弄清楚如何設置一個觸發器,當所有者按鈕被禁用時,將會將路徑的填充改爲紅色。

這有可能嗎?

回答

1

好吧......我想你需要在繼續之前修改幾件事情。 首先在XAML中,你應該使用這樣的代碼:

<Button Style="{DynamicResource IconButtonStyle}" IsEnabled="False" Content="{StaticResource _rect}"> 
    </Button> 

在這種情況下,我用我的資源定義的矩形。這是一個長方形的代碼:

<Rectangle Width="10" Height="10" Style="{StaticResource ContentButtonPathStyle}" x:Key="_rect"></Rectangle> 

你會明顯而不是使用矩形你的路...... 您會注意到樣式設置爲ContentButtonPathStyle

這是這種風格的代碼:

<Style x:Key="ContentButtonPathStyle" TargetType="{x:Type Rectangle}"> 
     <Style.Triggers> 
      <DataTrigger Binding="{Binding RelativeSource= 
       {RelativeSource Mode=FindAncestor, AncestorType={x:Type Button}}, Path=IsEnabled}" Value="False"> 
       <Setter Property="Fill" Value="Red"/> 
      </DataTrigger> 

      <DataTrigger Binding="{Binding RelativeSource= 
       {RelativeSource Mode=FindAncestor, AncestorType={x:Type Button}}, Path=IsEnabled}" Value="True"> 
       <Setter Property="Fill" Value="Black"/> 
      </DataTrigger> 
     </Style.Triggers> 
    </Style> 

請注意,您必須在矩形(路徑)之前定義ContentButtonPathStyle

最後一點是,您甚至不需要爲按鈕指定樣式。除非你需要它用於其他目的。

+0

這是完美的。謝謝你的幫助。 –

+0

;)不客氣。 –