How can I get a trigger to change the color of a TextBlock based on a DataContext Property?

后端 未结 3 1385
佛祖请我去吃肉
佛祖请我去吃肉 2021-01-02 17:11

Why does the following code get the runtime error:

Members of the Triggers collection must be of type EventTrigger

But the Event

相关标签:
3条回答
  • 2021-01-02 17:43

    There is a typo as you did not close out Style.Triggers. And I found I needed to use the property TextBlock.Background. Thanks, you got me to the solution.

        <TextBlock.Style>
            <Style TargetType="{x:Type TextBlock}">
                <Style.Triggers>
                    <DataTrigger Binding="{Binding Status}" Value="off">
                        <Setter Property="TextBlock.Background" Value="Red"/>
                     </DataTrigger>
                </Style.Triggers>
            </Style>
        </TextBlock.Style>
    
    0 讨论(0)
  • 2021-01-02 17:52

    That is because you can only set event triggers directly on the Trigger property..

    Use a style to achieve what you want:

    <Style x:Key="Triggers" TargetType="TextBlock">
        <Style.Triggers>
            <DataTrigger Binding="{Binding Status}" Value="off">
                <Setter Property="TextBlock.Background" Value="Red"/>
            </DataTrigger>
        </Style.Triggers>
    </Style>
    

    The following objects have Triggers collections that can contain the trigger types listed:

    FrameworkElement     Style, ControlTemplate, DataTemplate
    ----------------     ------------------------------------
    EventTrigger         EventTrigger
                         Trigger or MultiTrigger
                         DataTrigger or MultiDataTrigger
    
    0 讨论(0)
  • 2021-01-02 17:53

    You can do it in a style:

    <TextBlock Text="{Binding Status}">
        <TextBlock.Style>
            <Style TargetType="{x:Type TextBlock}">
                <Style.Triggers>
                    <DataTrigger Binding="{Binding Status}" Value="off">
                        <Setter Property="Background" Value="Red"/>
                    </DataTrigger>
                </Style.Triggers>
            </Style>
        </TextBlock.Style>
    </TextBlock>
    
    0 讨论(0)
提交回复
热议问题