Usage DataTrigger in WPF

允我心安 提交于 2019-12-07 07:17:24

I think you need just need to add RelativeSource={RelativeSource Self} to your bindings:

<Style x:Key="TextBoxStyle" TargetType="{x:Type TextBox}">
    <Style.Triggers>
        <DataTrigger Binding="{Binding IsEnabled, RelativeSource={RelativeSource Self}}" Value="True">
            <Setter Property="Background" Value="Yellow" />
        </DataTrigger>
        <DataTrigger Binding="{Binding IsReadOnly, RelativeSource={RelativeSource Self}}" Value="True">
            <Setter Property="Background" Value="Red" />
        </DataTrigger>
        <MultiDataTrigger>
            <MultiDataTrigger.Conditions>
                <Condition Binding="{Binding IsReadOnly, RelativeSource={RelativeSource Self}}" Value="True"/>
                <Condition Binding="{Binding IsEnabled, RelativeSource={RelativeSource Self}}" Value="True"/>
            </MultiDataTrigger.Conditions>
            <Setter Property="Background" Value="Green"/>
        </MultiDataTrigger>
    </Style.Triggers>
</Style>

There is still one problem however, I don't believe you will ever see a Red background because a TextBox with its IsEnabled property set to False has a built in background color into its control template that will take priority over your style's trigger's setter.

I think you'd have to redefine its control template to change the background color when the TextBox is disabled.

You are unecessarily complicating things

<Style x:Key="TextBoxStyle" TargetType="TextBox">
    <Style.Triggers>
        <Trigger Property="IsEnabled" Value="True">
            <Setter Property="Background" Value="Yellow"/>
        </Trigger>
        <Trigger Property="IsReadOnly" Value="True">
            <Setter Property="Background" Value="Red"/>
        </Trigger>
        <MultiTrigger>
            <MultiTrigger.Conditions>
                <Condition Property="IsEnabled" Value="True"/>
                <Condition Property="IsReadOnly" Value="True"/>
            </MultiTrigger.Conditions>
            <Setter Property="Background" Value="Green"/>
        </MultiTrigger>
    </Style.Triggers>
</Style>
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!