2015-12-26 34 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

;)不客气。 –