Usage DataTrigger in WPF

Anee picture Anee · May 3, 2011 · Viewed 8.4k times · Source

I have a TextBox control defined in XAML and I want to apply different background colors to the TextBox based on its IsReadOnly or IsEnabled properties. I used dataTriggers to actually switch between the colors as shown below:

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

And the TextBox is defined as shown below:

  <TextBox Name="sourceTextBox"  Margin="5,3,5,3" IsReadOnly="True" Style="{StaticResource TextBoxStyle}" />

But the problem is, the colors are not being applied properly.

Is there any problem with the above approach?

Answer

Dominic picture Dominic · May 3, 2011

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>