官方文档中对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>
    &lt;DataTemplate x:Key=&quot;PlaceTemplate&quot; DataType=&quot;{x:Type dataTrigger:Place}&quot;&gt;
    &lt;StackPanel Orientation=&quot;Horizontal&quot;&gt;
    &lt;TextBlock Text=&quot;{Binding Province,Mode=OneWay,StringFormat={}{0}- - &amp;#160;&amp;#160;}&quot;/&gt;
    &lt;TextBlock Text=&quot;{Binding Name,Mode=OneWay}&quot;/&gt;
    &lt;/StackPanel&gt;
    &lt;/DataTemplate&gt;

    </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>

WPF触发器(Trigger) - DataTrigger的更多相关文章

  1. WPF触发器(Trigger)

    WPF触发器(Trigger.DataTrigger.EventTrigger) WPF中有种叫做触发器的东西(记住不是数据库的trigger哦).它的主要作用是根据trigger的不同条件来自动更改 ...

  2. WPF触发器(Trigger、DataTrigger、EventTrigger)

    WPF中有种叫做触发器的东西(记住不是数据库的trigger哦).它的主要作用是根据trigger的不同条件来自动更改外观属性,或者执行动画等操作. WPFtrigger的主要类型有:Trigger. ...

  3. WPF 杂谈——Trigger触发器

    笔者在使用的WPF过程中,见过的触发器有三种:Trigger.DataTrigger.EventTrigger.其中最为常用的要属Trigger.至于触发器的作用就是当某个属性的值发生变化,应该去做某 ...

  4. [WPF系列]-基础系列 Property Trigger, DataTrigger & EventTrigger

    So far, we worked with styles by setting a static value for a specific property. However, using trig ...

  5. WPF根据ScrollViewer的滚动条出现与否来设置触发器Trigger

    先看一段代码 <Style.Triggers> <DataTrigger Binding="{Binding RelativeSource={RelativeSource ...

  6. WPF触发器(非数据库中的触发器)

    一.什么是触发器?触发器(Trigger)就是当某种条件满足后即完成相应逻辑功能的一部分程序组成.在当前的WPF中,Trigger一共有三种类型,它们分别是: (1)属性触发器:其对应的类是Trigg ...

  7. WPF 触发器例子

    WPF的触发器很强大,这里简单附上触发器的一个小例子,分别用XMAL和CS代码来实现一个功能,鼠标悬停在button上时改变字体颜色 1.XMAL代码如下: <Window x:Class=&q ...

  8. mysql之触发器trigger

    触发器(trigger):监视某种情况,并触发某种操作. 触发器创建语法四要素:1.监视地点(table) 2.监视事件(insert/update/delete) 3.触发时间(after/befo ...

  9. mysql之触发器trigger 详解

    为了梦想,努力奋斗! 追求卓越,成功就会在不经意间追上你 mysql之触发器trigger 触发器(trigger):监视某种情况,并触发某种操作. 触发器创建语法四要素:1.监视地点(table)  ...

随机推荐

  1. java.lang.NoClassDefFoundError: org/springframework/boot/context/embedded/FilterRegistrationBean

    昨天还好好的, 今天我的spring boot 项目就不能正常运行了! 出现: 018-07-06 10:01:41.776 WARN [mq-service,,,] 7 --- [ main] at ...

  2. kettle数据库连接使用变量

    新增db连接(密码也可以设置参数) 转换中,右键空白处,选择转换设置

  3. leetcode312

    class Solution { public int maxCoins(int[] iNums) { int[] nums = new int[iNums.length + 2]; int n = ...

  4. 如何学习DeepLearning

    多年来,科学家们为了搞清楚神经网络的运行机制,进行了无数次实验.但关于神经网络的内在运行方式,目前还没有系统性的理论,没有具体的路线可以指引你获得更好的性能.简单地下载开源工具包直接使用并不能跑出很棒 ...

  5. 保存xml报错 'UTF_8' is not a supported encoding name

    ArgumentException: 'UTF_8' is not a supported encoding name. For information on defining a custom en ...

  6. FM-分解机模型详解

    https://blog.csdn.net/zynash2/article/details/80029969 FM论文地址:https://www.csie.ntu.edu.tw/~b97053/pa ...

  7. Understanding ABI Files

    [Understanding ABI Files] ABI files can be generated using the eosio-cpp utility provided by eosio.c ...

  8. cdnbest里如何查看网站是否被缓存

    比如开启了强制缓存,如何查看缓存是否生效 本例以firefox浏览器查看,先打开浏览器,按下F12, 然后在浏览器是输入网址访问 如下图响应头里的 x-cache显示 Miss  from 就是没有缓 ...

  9. cdnbest区域里快速配置全部节点的缓存

    1.在cdn后台区域中自定义区域配置中添加下面代码,具体参数也可自行调整,代码解释在文档最下面有 <!--#start --> <config> <lang>zh_ ...

  10. JS获取URL中文参数乱码的解决方法

    浏览器URL参数值中带有汉字字符,在接收时直接获取会出现乱码,下面是解决方法(传递前不需要encodeURI): function getUrlVars() { var vars = [], hash ...