一、主要功能
用于WPF中控件不同属性的绑定关系。例如根据Text的不同,TextBlock的Text显示的foreground也不同。
二、解析
<TextBlock Text="{Binding Category}" x:Name="xColor" FontSize="15" FontWeight="Black" FontStyle="Italic" Foreground="{Binding Category , Converter={StaticResource ColorConvert} }"/>
这段代码的作用是将TextBlock的foreground绑定到category属性。但是由于不是同一种类型,因此需要一个转换。在绑定的属性里面,有一个转换器属性Converter,这里绑定的是一个静态资源
<Window.Resources>
<convert:ColorConvert x:Key="ColorConvert"/>
</Window.Resources>
convert是引用的命名空间,然后ColorConvert是里面的转换类。
public class ColorConvert : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
if(value == null) return Brushes.White;
switch (value.ToString())
{
case "Electronics":
return Brushes.Blue;
case "Home":
return Brushes.Green;
case "Sports":
return Brushes.Orange;
default: return Brushes.White;
}
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
throw new NotImplementedException();
}
}
所有转换类都必须继承IValueConverter接口,然后实现其中的两个方法,Convert和ConvertBack
其中Convert是主要起作用的类。参数介绍:
value:
既是绑定的属性值,在此实例中为category。
targetType:
类型,暂时不用管。
object parameter:
对应的是传递的转换参数,例如 ConverterParameter={StaticResource auto} 这个是写在绑定里面的。对应的staticResource 也是写在Windows.Resources 资源里面的。
CultureInfo culture:
暂时不用管
返回值:
返回值需要返回当前绑定属性对应的值。如果是颜色的话,那么返回值就应该是Brushes类型的值。对于其他类型,例如可见度这些也是这样。