在WPF中应用数据绑定时经常需要做一些简单的逻辑判断。
比如ViewModel中有一个HasError(布尔值)的属性表示是否有错误。我需要将它绑定于Button的IsEnable属性上,即:当没有错误时Button可用。这时就需要将HasError取反。WPF默认的绑定引擎是不支持的。
还有一种情况比如ViewModel中有一个Sex(int值)的属性表示性别,我需要将它绑定到TextBlock上,当值为1时显示男,值为2时显示女。WPF默认绑定也是不支持这种判断的。
于是一个通用的值转换器就诞生了,用法如下:
IsReverse参数表示是否取返,如果转换的值为true则变为false,反之亦然。
Alias参数表示将值映射为字符串,other表示当遇到没有指定的值时显示的文本
另外bool to Visibility的转换可以自动进行,不需要指定参数。
有意见欢迎指正
完整代码如下:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Data;
using System.Windows;
namespace MoodSunshiny.WPF.Converter
{
///
/// 一个通用的类型转换器,可以提供更多转换控制参数
///
public class GenericTypeConverter : IValueConverter
{
///
/// 是否反转转换源参数值
/// 仅对bool类型的值有效
///
private bool IsReverse { get; set; }
///
/// 用于将转换结果映射为其它字符串
/// 例如:Alias=True:是|False:否
///
private Dictionary
WPF,值通,用的,类型,转换器,完整,代码,在,WPF,