基于文本的长度WPF文本框背景颜色
问题描述:
我在ListView的ItemTemplate一个文本框。我想文本框的背景颜色变为红色每当长度大于75个字符,我需要的背景色,以更新的用户类型。什么是WPF实现这一目标的最佳途径?
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?
答
我相信这样的事情会工作。它会要求你写你自己的背景颜色的转换器。
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}}"
...
/>
另一种选择是使用一个DataTrigger像的下方。这还需要一个转换器,以检查是否字符串的长度超过75
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>