WPF DataTrigger的两个用法

 

 

 

1.用在textbox等输入控件上,验证输入是否合法。

首先定义一个Converter,

1 class DataConverter : IValueConverter
2 {
3 object IValueConverter.Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
4 {
5 if (value == null) return false;
6 if (string.IsNullOrEmpty(value.ToString())) return false;
7 if (!Regex.IsMatch(value.ToString(), "^[1-9]\\d*$")) return false;
8 return Convert.ToInt32(value) < 100;
9 }
10
11 object IValueConverter.ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
12 {
13 return null;
14 }
15 }

 

 

2.Xaml里面这样子写,意思是输入的数字,如果小于100则显示为红色。

 

代码
1 <TextBox Canvas.Left="146" Canvas.Top="199" Height="23" Name="textBox2" Width="120" Margin="62,47,321,241">
2 <TextBox.Resources>
3 <Style TargetType="{x:Type TextBox}">
4 <Style.Triggers>
5 <DataTrigger Binding="{Binding RelativeSource={RelativeSource Self},Path=Text,Converter={StaticResource dc}}" Value="True">
6 <Setter Property="Foreground" Value="Red" ></Setter>
7 </DataTrigger>
8 </Style.Triggers>
9 </Style>
10 </TextBox.Resources>
11 </TextBox>

 

3.combox等列表控件里面,也可以用做数据筛选。下面例子中筛选出小于100的项目,红色显示

数据源定义为:

 

代码
1 List<object> objList = new List<object>();
2 for (int i = 0; i < 200; i += 10)
3 {
4 objList.Add(new { Display = "d" + i.ToString(), Tag = i.ToString() });
5 }
6
7 comboBox1.ItemsSource = objList;

 

 

Xaml:

 

代码
1 <ComboBox Canvas.Left="694" Canvas.Top="24" Height="23" Name="comboBox1" Width="120" Margin="205,47,178,241">
2 <ComboBox.ItemTemplate>
3 <DataTemplate>
4 <StackPanel Orientation="Horizontal" >
5 <TextBlock Text="{Binding Display}" Name="t1"></TextBlock>
6 <TextBlock Text="--" Name="t2"/>
7 <TextBlock Text="{Binding Tag}" Name="t3"></TextBlock>
8 </StackPanel>
9 <DataTemplate.Triggers>
10 <DataTrigger Binding="{Binding Path=Tag,Converter={StaticResource dc}}" Value="True">
11 <Setter Property="Foreground" TargetName="t1" Value="Red" />
12 <Setter Property="Foreground" TargetName="t2" Value="Red" />
13 <Setter Property="Foreground" TargetName="t3" Value="Red" />
14 </DataTrigger>
15 </DataTemplate.Triggers>
16 </DataTemplate>
17 </ComboBox.ItemTemplate>
18 </ComboBox>

 

源码下载 https://files.cnblogs.com/xiaokang088/WpfDataTrigger.rar

posted @ 2010-11-17 17:26  xiaokang088  阅读(15681)  评论(0编辑  收藏  举报