Binding之数据转换
来源:互联网 发布:预测股票涨跌软件 编辑:程序博客网 时间:2024/05/24 04:29
Binding是源对象与目标对象之间的桥梁,如果两者类型存在差异,除了系统的隐式转换,比如基础数据类型之间的转换,其他就需要显示实现转换,其关键是实现IValueConverter接口。
关键点有如下几点:
1、实现IValueConverter接口
原型:
// 摘要: // 提供一种将自定义逻辑应用于绑定的方式。 public interface IValueConverter { // 摘要: // 转换值。 // // 参数: // value: // 绑定源生成的值。 // // targetType: // 绑定目标属性的类型。 // // parameter: // 要使用的转换器参数。 // // culture: // 要用在转换器中的区域性。 // // 返回结果: // 转换后的值。如果该方法返回 null,则使用有效的 null 值。 object Convert(object value, Type targetType, object parameter, CultureInfo culture); // // 摘要: // 转换值。 // // 参数: // value: // 绑定目标生成的值。 // // targetType: // 要转换到的类型。 // // parameter: // 要使用的转换器参数。 // // culture: // 要用在转换器中的区域性。 // // 返回结果: // 转换后的值。如果该方法返回 null,则使用有效的 null 值。 object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture); }Convert是指源数据到目标数据的转换,ConvertBack是指目标数据到源数据的转换
举例:
public class StateToSourceConverter : IValueConverter { /// <summary> /// 源数据State状态转换成BOOL类型 /// </summary> public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture) { State source = (State)value; switch (source) { case State.Unknown: return null; case State.Locked: return false; case State.Available: default: return null; } } public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture) { bool? target = (bool?)value; switch (target) { case true: return State.Available; case false: return State.Locked; case null: default: return State.Unknown; } } }2、设置Binding对象中的Converter属性
在XAML中设置该属性时,可直接引用已定义好的实现IValueConverter类作为静态资源,即在XAML中添加WindowResource,如:
<Window.Resources> <local:CategoryToSourceConverter x:Key="cts"/> <local:StateToSourceConverter x:Key="sts"/> </Window.Resources>引用转换类:
<CheckBox IsThreeState="True" IsChecked="{Binding State,Converter={StaticResource sts}}"/>
总结:最关键一点是还是在于数据转换发生在数据源和目标对象任何一方面变化时都会发生数据转换,调用Convert和ConvertBack方法
- Binding之数据转换
- WPF应用Binding之数据转换
- Binding的数据转换
- Binding- 数据转换
- WPF Data Binding之数据的转换和校验【四】
- WPF中的binding(十一)- Binding数据的转换
- SliverLight-Binding之数据绑定
- Binding的数据转换(Data Converter)
- 数据绑定(十)Binding的数据转换
- WPF应用Binding之数据有效性检测
- android数据绑定之Data Binding
- 数据绑定之Binding简单绑定
- 数据绑定之Binding双向绑定
- SliverLight-Binding之动态修改和数据绑定
- SAPUI5 (11) - 数据绑定之属性绑定(property binding)
- SAPUI5 (13) - 数据绑定之聚合绑定(aggregation binding)
- SAPUI5 (14) - 数据绑定之元素绑定(element binding)
- WPF 之 Binding 数据驱动UI—实战
- 欧拉函数性质
- centos6.4最小安装版 pppoe上网配置 无线上网配置
- STL中的vector_map
- u-boot-2009.11在mini2440上的移植,关于SDRAM&NOR&NAND启动的几点疑惑
- LA 3938 - "Ray, Pass me the dishes!"(线段树)
- Binding之数据转换
- 汇编指令参考
- JNI的一个未解问题
- td文字超出设定宽度变成点
- newInstance()和new()
- java 如何得到文件的系统图标
- Mini2440 DM9000 驱动分析(一)
- Why do people hate Windows?
- c++学习之头文件的使用