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
2009-12-16 17:37:16
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
2009-12-16 18:07:39
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
2009-12-16 18:25:04
Thanks very much, that worked!
dhysong
2009-12-16 18:39:09
What about the 2nd one? Did you ever get that one working too?
Taylor Leese
2009-12-16 18:50:15
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
2009-12-16 18:56:59
I think the second one just needs <Style.Triggers> tags wrapped abour the <DataTrigger>.
Ben Collier
2009-12-16 19:23:54
Ah, absolutely correct. I forgot that while I was typing it in. I updated the answer.
Taylor Leese
2009-12-16 20:32:12