官方文档中对DataTrigger的介绍
Represents a trigger that applies property values or performs actions when the bound data meets a specified condition.
某词典的翻译:
当绑定的数据满足指定的条件时,应用(指定的)属性或执行操作的触发器
下面我演示一遍官方文档中的示例,根据官网的描述,建立实体类,然后编写前台代码
-
先来张效果图
- 通过DataTrigger,将省份为江苏省的Item项的文字颜色设置成了红色;
- 然后又通过MultoDataTrigger,将省份为江西省市为南昌的Item设置的背景设置成浅蓝色
- 关键部分代码:
<Page.Resources> <dataTrigger:Places x:Key="Places"/> <Style TargetType="ListBoxItem"> <Style.Triggers> <DataTrigger Binding="{Binding Path=Province}" Value="江苏省"> <Setter Property="Foreground" Value="Red"/> </DataTrigger> <MultiDataTrigger> <MultiDataTrigger.Conditions> <Condition Binding="{Binding Path=Province}" Value="江西省"/> <Condition Binding="{Binding Path=Name}" Value="南昌"/> </MultiDataTrigger.Conditions> <Setter Property="Background" Value="Cyan"/> </MultiDataTrigger> </Style.Triggers> </Style> <DataTemplate x:Key="PlaceTemplate" DataType="{x:Type dataTrigger:Place}"> <StackPanel Orientation="Horizontal"> <TextBlock Text="{Binding Province,Mode=OneWay,StringFormat={}{0}- -   }"/> <TextBlock Text="{Binding Name,Mode=OneWay}"/> </StackPanel> </DataTemplate> </Page.Resources> <Grid> <ListBox Margin="20 30" MaxWidth="300" MaxHeight="250" ItemsSource="{StaticResource Places}" ItemTemplate="{StaticResource PlaceTemplate}"> </ListBox> </Grid>
-
新建一个测试项目:
-
添加两个类:
- Place
- Places
namespace Demo.DataTrigger { public class Place { public string Name { get; set; } public string Province { get; set; } public Place(string name,string province) { Name = name; Province = province; } } } using System.Collections.ObjectModel; namespace Demo.DataTrigger { public class Places:ObservableCollection<Place> { public Places() { Add(new Place("南京", "江苏省")); Add(new Place("宁波", "浙江省")); Add(new Place("苏州", "江苏省")); Add(new Place("南通", "江苏省")); Add(new Place("深圳", "广州省")); Add(new Place("芜湖", "安徽省")); Add(new Place("东菀", "广东省")); Add(new Place("无锡", "江苏省")); Add(new Place("南昌", "江西省")); } } }
-
xaml代码
<Page.Resources> <dataTrigger:Places x:Key="Places"/> <Style TargetType="ListBoxItem"> <Style.Triggers> <DataTrigger Binding="{Binding Path=Province}" Value="江苏省"> <Setter Property="Foreground" Value="Red"/> </DataTrigger> <MultiDataTrigger> <MultiDataTrigger.Conditions> <Condition Binding="{Binding Path=Province}" Value="江西省"/> <Condition Binding="{Binding Path=Name}" Value="南昌"/> </MultiDataTrigger.Con