原文:数据绑定(十)Binding的数据转换

当Source端Path所关联的数据与Target端目标属性数据类型不一致时,需要添加数据转换器,数据转换器是一个自定义的类,这个类需要实现IValueConverter接口,这个接口有两个方法需要实现:Convert和ConvertBack,当数据从Source流向Target时,将调用Convert方法,反之,将调用ConvertBack方法

例子,首先定义飞机类型

    public enum Category
{
Bomber,
Fighter
} public enum State
{
Available,
Locked,
Unknown
} public class Plane
{
public Category Category { get; set; }
public string Name { get; set; }
public State State { get; set; }
}

Plane类型的Category将在界面上转换为图片,而State类型将会转换成界面上的CheckBox显示,由于存在两个转换,因此需要提供两个Converter,第一个转换是做Category类型与字符类型的转换,字符串是图片的路径

    class CategoryToSourceConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
Category c = (Category)value;
switch (c)
{
case Category.Bomber:
{
return @"\Icons\close.png";
}
case Category.Fighter:
{
return @"\Icons\closeing.png";
}
default:
{
return null;
}
}
} public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
return new NotImplementedException();
}
}

由于UI上不能修改图片,所以只实现了从Source到Target的转换

另一个转换用于将State数据转换为bool?

    public class StateToNullableBoolConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
State s = (State)value;
switch (s)
{
case State.Locked:
{
return false;
}
case State.Available:
{
return true;
}
case State.Unknown:
default:
{
return null;
}
}
} public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
bool? nb = (bool?)value;
switch (nb)
{
case true:
{
return State.Available;
}
case false:
{
return State.Locked;
}
case null:
default:
{
return State.Unknown;
}
}
}
}

界面代码:

<Window x:Class="WpfApplication1.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:WpfApplication1"
Title="MainWindow" Height="275" Width="275">
<Window.Resources>
<local:CategoryToSourceConverter x:Key="cts" />
<local:StateToNullableBoolConverter x:Key="stnb" />
</Window.Resources>

<StackPanel Background="LightBlue">
<ListBox x:Name="listBoxPlane" Height="160" Margin="5">
<ListBox.ItemTemplate>
<DataTemplate>
<StackPanel Orientation="Horizontal">
<Image Width="20" Height="20" Source="{Binding Path=Category, Converter={StaticResource cts}}" />
<TextBlock Text="{Binding Path=Name}" Width="60" Margin="80,0" />
<CheckBox IsThreeState="True" IsChecked="{Binding Path=State, Converter={StaticResource stnb}}" />

</StackPanel>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
<Button x:Name="buttonLoad" Content="Load" Height="25" Margin="5,0" Click="buttonLoad_Click" />
<Button x:Name="buttonSave" Content="Save" Height="25" Margin="5,0" Click="buttonSave_Click" />
</StackPanel>
</Window>

加粗的部分是XAML中对转换器的使用,后台代码中实现了Load和Save两个按钮的点击事件

        private void buttonLoad_Click(object sender, RoutedEventArgs e)
{
List<Plane> planeList = new List<Plane>()
{
new Plane(){Category=Category.Bomber, Name="B-1", State=State.Unknown},
new Plane(){Category=Category.Bomber, Name="B-2", State=State.Unknown},
new Plane(){Category=Category.Fighter, Name="F-22", State=State.Unknown},
new Plane(){Category=Category.Fighter, Name="Su-47", State=State.Unknown},
new Plane(){Category=Category.Bomber, Name="B-52", State=State.Unknown},
new Plane(){Category=Category.Fighter, Name="J-10", State=State.Unknown}
}; listBoxPlane.ItemsSource = planeList;
} private void buttonSave_Click(object sender, RoutedEventArgs e)
{
StringBuilder sb = new StringBuilder();
foreach (Plane p in listBoxPlane.Items)
{
sb.AppendLine(string.Format("Category={0}, Name={1}, State={2}", p.Category, p.Name, p.State));
}
File.WriteAllText(@"d:\PlaneList.txt", sb.ToString());
}

界面效果如图:

当改变checkbox的选中状态时,Plane对象中的值会发生变化

最新文章

  1. Entity Framework 教程——创建实体数据模型
  2. 【实战Java高并发程序设计6】挑战无锁算法:无锁的Vector实现
  3. 转 C# 给某个方法设定执行超时时间
  4. 碎片事物的提交 commitAllowingStateLoss()
  5. Git版本控制工具(一)----git的安装及创建版本库
  6. WordPress博客教程:博客赚钱
  7. Inside Kolla - 03 下载Kolla
  8. [BS] 小知识点总结-01
  9. asp.net等项目编译失败的原因之不能写入
  10. Covariance and Contravariance in C#, Part One
  11. poj棋盘分割(记忆化)
  12. asp.net mvc4 Controller与Action执行过程的研究(学习笔记)
  13. 使用wampserver安装Composer的注意事项
  14. MVC折线图应用
  15. title:EL表达式获取Map里面的数值失败的问题
  16. XStream 用法汇总
  17. Java动手动脑——多态和继承
  18. 解决iPhone Safari 兼容性CSS背景显示不全问题
  19. ACE如何生成VS工程之mwc.pl用法
  20. node express使用

热门文章

  1. IE浏览器下css hack
  2. Redis的增删改查命令总结与持久化方式
  3. IHookHelper的用法
  4. Windows 查看硬盘ID(diskpart命令)
  5. 【hdu 3863】No Gambling
  6. [DevExpress]DevExpress 中 汉化包 汉化方法
  7. CocoaPods详解之(三)----制作篇
  8. hive 导出数据的几种方式
  9. Enhancing network controls in mandatory access control computing environments
  10. Vue Router的官方示例改造