首页 技术 正文
技术 2022年11月14日
0 收藏 664 点赞 4,878 浏览 5205 个字

官方文档中对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>
相关推荐
python开发_常用的python模块及安装方法
adodb:我们领导推荐的数据库连接组件bsddb3:BerkeleyDB的连接组件Cheetah-1.0:我比较喜欢这个版本的cheeta…
日期:2022-11-24 点赞:878 阅读:9,103
Educational Codeforces Round 11 C. Hard Process 二分
C. Hard Process题目连接:http://www.codeforces.com/contest/660/problem/CDes…
日期:2022-11-24 点赞:807 阅读:5,579
下载Ubuntn 17.04 内核源代码
zengkefu@server1:/usr/src$ uname -aLinux server1 4.10.0-19-generic #21…
日期:2022-11-24 点赞:569 阅读:6,427
可用Active Desktop Calendar V7.86 注册码序列号
可用Active Desktop Calendar V7.86 注册码序列号Name: www.greendown.cn Code: &nb…
日期:2022-11-24 点赞:733 阅读:6,199
Android调用系统相机、自定义相机、处理大图片
Android调用系统相机和自定义相机实例本博文主要是介绍了android上使用相机进行拍照并显示的两种方式,并且由于涉及到要把拍到的照片显…
日期:2022-11-24 点赞:512 阅读:7,834
Struts的使用
一、Struts2的获取  Struts的官方网站为:http://struts.apache.org/  下载完Struts2的jar包,…
日期:2022-11-24 点赞:671 阅读:4,917