C# IValueConverter接口用法举例

  • A+
所属分类:.NET技术
摘要

 01—  介绍  IValueConverter接口位于名称空间System.Windows.Data,接口定义了Convert和ConvertBack两组方法:

 

01

 

 

介绍

 

 

IValueConverter接口位于名称空间System.Windows.Data,接口定义了Convert和ConvertBack两组方法:

 public interface IValueConverter     {         object Convert(object value, Type targetType, object parameter, CultureInfo culture);         object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture);     } } 

  

在界面控件所需数据类型或格式和后台绑定的数据不一致时,往往需要借助IValueConverter接口进行转换。

 

02

举例

 

  •   界面添加一个表格控件datagrid,绑定数据结构StudentList,StudentList这是一个ObservableCollection<Students>集合;

  • Students数据模型定义如下:其中重写了ToString方法,并定义了四个属性,分别是Id,Name ,Age 和AgeValidate ,AgeValidate 用来验证数据,即年龄小于16或者大于21,时界面字体显示红色

  •  [AddINotifyPropertyChangedInterface]     public class Students      {         private int id;         public int Id         {             get { return id; }             set             {                 id = value;             }         }         public string Name { get; set; }          private int age;         public int Age          {             get { return age; }             set             {                 age = value;                 if(age < 16 || age > 21 )                 {                     AgeValidate = true;                 }                 else                 {                     AgeValidate = false;                 }             }         }          public bool AgeValidate { get; set; }         public override string ToString()         {             StringBuilder report = new StringBuilder();             report.AppendLine($"[Id]  = [{Id}]");             report.AppendLine($"[Name]  = [{Name}]");             report.AppendLine($"[Age]  = [{Age}]");             report.AppendLine($"[AgeValidate]  = [{AgeValidate}]");             return report.ToString();         }     } 

      界面前台绑定:主要是通过这句

  •  Foreground="{Binding AgeValidate,Converter={StaticResource ShowColorConverter}}" 

      datagrid全部的代码如下:

  •  <DataGrid Name="dgSourceData" AutoGenerateColumns="False" ItemsSource="{Binding StudentList}"                    ContextMenu="{Binding menu1}" RowHeaderWidth="30"  SelectedItem ="{Binding SelectedItems}" SelectionMode="Single" SelectionUnit="Cell"                                 cal:Message.Attach="[Event SelectionChanged]=[GridControl_SelectionChanged($source,$eventArgs)];"                                 CellEditEnding="dgSourceData_BeginningEdit" SelectionChanged="dgSourceData_SelectionChanged" >             <DataGrid.Columns>                 <DataGridTextColumn Header="Name"  Binding="{ Binding Path=Name}" MinWidth="68"/>                 <DataGridTemplateColumn  Header="Age"  MinWidth="68" >                     <DataGridTemplateColumn.CellTemplate>                         <DataTemplate>                             <TextBox Text="{Binding Path=Age,Mode=TwoWay,UpdateSourceTrigger=PropertyChanged}"                                       Foreground="{Binding AgeValidate,Converter={StaticResource ShowColorConverter}}" />                         </DataTemplate>                     </DataGridTemplateColumn.CellTemplate>                 </DataGridTemplateColumn>                 <DataGridTextColumn Header="Id"  Binding="{ Binding Path=Id}" MinWidth="48"/>             </DataGrid.Columns>         </DataGrid> 

      定义资源

  •  <UserControl.Resources>         <converters:ShowColorConverter x:Key="ShowColorConverter" />     </UserControl.Resources> 

      

    IValueConverter接口实现:注意需要将object类型的value转换为我们的目标类型bool量

     

    public class ShowColorConverter : IValueConverter     {         public object Convert(object value, Type targetType, object parameter, CultureInfo culture)         {             var flag = (bool)value;             if (flag)             {                 return "Red";             }             else             {                 return "Black";             }         }          public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)         {             throw new NotImplementedException();         }     } 

     

    项目源码

    百度网盘:链接:https://pan.baidu.com/s/1LmBp1XkXIYz01wyrFQIyYQ

    提取码:添加小编获取

    技术群:添加小编微信并备注进群小编微信:mm1552923   公众号:dotNet编程大全