views:

24

answers:

1

Why doesn't this simple Style work for a TextBox? I expect the background/foreground colors to change when I change the text between "0" and "1" ...

<Style x:Key="TextBoxStyle" TargetType="{x:Type TextBox}">
           <Setter Property="Background" Value="Gray"/>

            <Style.Triggers>               
                <!-- If the Textbox holds a value of 1, then update the foreground/background -->
                <DataTrigger Binding="{Binding Path=Text}" Value="1">
                    <Setter Property="Foreground" Value="Black"/>
                    <Setter Property="Background" Value="White"/>
                </DataTrigger>

                <!-- If the Textbox holds a value of 0, then update the foreground/background -->
                <DataTrigger Binding="{Binding Path=Text}" Value="0">
                    <Setter Property="Foreground" Value="White"/>
                    <Setter Property="Background" Value="Black"/>
                </DataTrigger>
            </Style.Triggers>
 </Style>
+3  A: 

You use a DataTrigger but better in this case would be a trigger:

    <Trigger Property="Text" Value="1">
        <Setter Property="Foreground" Value="Black"/>
        <Setter Property="Background" Value="White"/>
    </Trigger>
HCL
+1 It works. I'd like to see some elaboration as to why. Looking at the [MSDN documentation](http://msdn.microsoft.com/en-us/library/system.windows.datatrigger.aspx), it seems like a `DataTrigger` isn't appropriate in this case because the `TextBox` isn't databound; a `DataTrigger` expects to be bound to a property of the object *bound* to the `TextBox`, not the `Text` property of the TextBox itself. Whereas a [Trigger](http://msdn.microsoft.com/en-us/library/system.windows.trigger.aspx) can be bound to any Dependency Property.
djacobson
Thanks! Works like the charm, and thanks for the explanation! :)
Max
Trigger is definetly the way to go but technically you could use the DataTrigger and use a RelativeSource on the binding such as Binding="{Binding Text, RelativeSource={RelativeSource Self}}"
David Rogers