WPF触发器(Trigger) - DataTrigger
官方文档中对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.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}- - &#160;&#160;}"/> <TextBlock Text="{Binding Name,Mode=OneWay}"/> </StackPanel> </DataTemplate>
</Page.Resources>
<ListBox Margin="20 30"
MaxWidth="300" MaxHeight="250"
ItemsSource="{StaticResource Places}"
ItemTemplate="{StaticResource PlaceTemplate}">
</ListBox>
下面的一个例子是我在项目中遇到的
Image控件的Source属性通过数据绑定到后台属性的一个图片的路径,当后台属性为null时,默认一个路径提供给Image控件,恰巧这两天看到一个DataTrigger,就想着用它来实现,结果经历了一番周折,最终通过一个Converter值转化器和DataTrigger配合实现了,下面演示代码;
先看前台xaml代码:
<StackPanel Orientation="Horizontal">
<StackPanel.Resources>
<dataTrigger:PathValidateConverter x:Key="Converter"></dataTrigger:PathValidateConverter>
</StackPanel.Resources>
<Image>
<Image.Style>
<Style TargetType="Image">
<Style.Triggers>
<DataTrigger Binding="{Binding Path=ThumbnailPath,Mode=OneWay,Converter={StaticResource Converter}}"
Value="False">
<Setter Property="Source" Value="/Resources/Images/icons8-thumbnails-80.png"/>
</DataTrigger>
<DataTrigger Binding="{Binding Path=ThumbnailPath,Mode=OneWay,Converter={StaticResource Converter}}"
Value="True">
<Setter Property="Source" Value="E:\\Media\\Images\\Src\\s.png"/>
</DataTrigger>
</Style.Triggers>
</Style>
</Image.Style>
</Image>
<CheckBox Content="设置ThumbnailPath为有效的路径值"
Checked="CheckBox_Checked" Unchecked="CheckBox_Unchecked"/>
</StackPanel>
然后看一下那个简单的值转换器,就是通过File.Exists()方法来判断文件路径是否合法,不合法则返回false:
PathValidatorConverter
using System; using System.Globalization; using System.IO; using System.Windows.Data;
namespace Demo.DataTrigger
{
class PathValidateConverter:IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
if (value == null) return false;
if (value.GetType() != typeof(string)) throw new ArgumentOutOfRangeException(nameof(value));return File.Exists((string) value); } public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) { throw new NotImplementedException(); } }
}
由于这个项目我只是用来演示的,所以就懒得去建立ViewModel,直接把代码xaml的隐藏类作为DataContext,后台代码中定义一个依赖属性来表示图片路径:
public string ThumbnailPath { get => (string)GetValue(MyPropertyProperty); set => SetValue(MyPropertyProperty, value); }
// Using a DependencyProperty as the backing store for MyProperty. This enables animation, styling, binding, etc...
public static readonly DependencyProperty MyPropertyProperty =
DependencyProperty.Register(nameof(ThumbnailPath), typeof(string), typeof(Demo),
new FrameworkPropertyMetadata(null));
还有两个函数处理前台CheckBox的Checked和UnChecked事件:
private void CheckBox_Checked(object sender, RoutedEventArgs e)
{
ThumbnailPath = @"E:\\Media\\Images\\Src\\s.png";
}
private void CheckBox_Unchecked(object sender, RoutedEventArgs e)
{
ThumbnailPath = null;
}
当CheckedBox被选中时,或将ThumbnailPath设置成一个图片的绝对路径,而没被选中时,ThumbnailPath则被置为null
最终效果如下:
- 不选中CheckBox时:
- 选中时:
总结,DataTrigger可以在某些数据发生改变时设置一些UI的样式,应该还有不少应用,WPF里的东西感觉比较多,有些东西用完不记录东西,容易遗忘,所以多记录以下总是好的.另外,各位大虾,你们如果有啥思路实现上面第二个例子的效果,欢迎指教....我暂时就先这么用了
</div>