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方法