1.用在textbox等输入控件上,验证输入是否合法。
<Window.Resources> <Style TargetType="TextBox"> <Style.Triggers> <!--Binding属性会把数据源不断送过来,送过来的值与Value属性一致就被触发。--> <DataTrigger Binding="{Binding RelativeSource={x:Static RelativeSource.Self},Path=Text.Length}" Value="0"> <!--这里使用RelativeSource将控件自己作为数据源,当文本框文本长度为0时触发--> <!--也可以用Converter来转换成Bool值验证长度、格式(Convert方法中用正则表达式验证)等 <DataTrigger Binding="{Binding RelativeSource={RelativeSource Self},Path=Text,Converter={StaticResource dc}}" Value="True"> --> <Setter Property="BorderBrush" Value="Red"/> </DataTrigger> </Style.Triggers> </Style > </Window.Resources> <TextBox Height="23" HorizontalAlignment="Left" Margin="50,66,0,0" Name="textBox1" VerticalAlignment="Top" Width="120" /> <TextBox Height="23" HorizontalAlignment="Left" Margin="50,108,0,0" Name="textBox2" VerticalAlignment="Top" Width="120" />
运行结果:文本框文本长度为0,则显示设置的样式。
2.combox等列表控件里面,也可以用做数据筛选。
对于集合数据或者列表数据,满足一定条件的就显示成另外一种样式。
1)先添加一个转化器:
class Text2BoolConvert : IValueConverter { public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture) { if (value == null) return false; if (string.IsNullOrEmpty(value.ToString())) return false; if (!Regex.IsMatch(value.ToString(), "^[1-9]\\d*$")) return false; return int.Parse(value.ToString()) < 100; } public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture) { throw new NotImplementedException(); } }