将多个触发器重构为一个

时间:2014-09-22 22:30:35

标签: wpf xaml

是否可以将其减少为单个触发器?

<Style x:Key="StatusTextBlock" TargetType="{x:Type TextBlock}">
    <Style.Triggers>
        <DataTrigger Binding="{Binding Path=Text, 
            RelativeSource={RelativeSource Self}}" Value="Running">
            <Setter Property="Foreground" Value="Green"></Setter>
        </DataTrigger>
        <DataTrigger Binding="{Binding Path=Text, 
            RelativeSource={RelativeSource Self}}" Value="Paused">
            <Setter Property="Foreground" Value="Yellow"></Setter>
        </DataTrigger>
        <DataTrigger Binding="{Binding Path=Text, 
            RelativeSource={RelativeSource Self}}" Value="Stopped">
            <Setter Property="Foreground" Value="Red"></Setter>
        </DataTrigger>
    </Style.Triggers>
</Style>

1 个答案:

答案 0 :(得分:0)

如果"Running""Stopped"是唯一两个可用案例,您可以将其中一个设置为属性,并且只使用一个触发器:

<Style x:Key="StatusTextBlock" TargetType="{x:Type TextBlock}">
    <Setter Property="Foreground" Value="Green" /> <!--default case == Running -->
    <Style.Triggers>
        <DataTrigger Binding="{Binding Path=Text, 
            RelativeSource={RelativeSource Self}}" Value="Stopped">
            <Setter Property="Foreground" Value="Red"></Setter>
        </DataTrigger>
    </Style.Triggers>
</Style>