tags:

views:

433

answers:

1

I have a textbox in a listview itemtemplate. I want to change the background color of the textbox to red whenever the length is greater than 75 characters, and I need the background color to update as the user types. What is the best way to achieve this in WPF?

+6  A: 

I believe something like this would work. It would require you to write your own background color converter.

<TextBox 
    Background="{Binding RelativeSource={RelativeSource self},
        Path=Text, 
        UpdateSourceTrigger=PropertyChanged,
        Converter={StaticResource backgroundColorConverter}}" 
    ... 
/>

Another option would be to use a DataTrigger like below. This would also require a converter to check if the length of the string was more than 75.

<TextBox>
    ....
    <TextBox.Style>
        <Style TargetType="{x:Type TextBox}">
            <Setter Property="Background" Value="YourDefaultColor" />
            <Style.Triggers>
                <DataTrigger Binding="{Binding ElementName=YourTextBox, Path=Text, Converter={StaticResource textLengthColorConverter}}" Value="True">
                    <Setter Property="Background" Value="Red" />
                </DataTrigger>
            </Style.Triggers>
        </Style>
    </TextBox.Style>
</TextBox>
Taylor Leese
The first one fires only after the textbox loses focus. I get a "A value of type 'DataTrigger' cannot be added a collection or dictionary of type 'SetterBaseCollection' on the second one.
dhysong
Use UpdateSourceTrigger=PropertyChanged for the first one. The default is LostFocus for TextBox's. I'd need to see your code to help with the 2nd error.
Taylor Leese
Thanks very much, that worked!
dhysong
What about the 2nd one? Did you ever get that one working too?
Taylor Leese
I'll have to go back and test it later. I've spent too much time trying to get this to work, and I need to move on. Thanks again!
dhysong
I think the second one just needs <Style.Triggers> tags wrapped abour the <DataTrigger>.
Ben Collier
Ah, absolutely correct. I forgot that while I was typing it in. I updated the answer.
Taylor Leese