一、目的:应用MarkupExtention定义IValueConverter,使得应用起来更简单和高效
二、实现
public abstract class MarkupValueConverterBase : MarkupExtension, IValueConverter
{
public abstract object Convert(object value, Type targetType, object parameter, CultureInfo culture);
public virtual object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
throw new NotImplementedException();
}
public override object ProvideValue(IServiceProvider serviceProvider)
{
return this;
}
}
三、环境
VS2022,.Net 7
四、示例
自定义一个DateTime时间转换年龄的转化器
public class GetAgeConverter : MarkupValueConverterBase
{
public override object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
if (value is DateTime dateTime)
{
DateTime now = DateTime.Now;
int age = now.Year - dateTime.Year;
if (now.Month < dateTime.Month || (now.Month == dateTime.Month && now.Day < dateTime.Day))
{
age--;
}
return age > 0 ? age : 0;
}
return this.DefaultValue;
}
}
使用方法
<TextBlock Text="{Binding Source={x:Static s:DateTime.MinValue},Converter={local:GetAgeConverter DefaultValue=50}}"/>
输出结果
五、需要了解的知识点
IValueConverter 接口 (System.Windows.Data) | Microsoft Learn
MarkupExtension 类 (System.Windows.Markup) | Microsoft Learn
六、源码地址
GitHub - HeBianGu/WPF-ControlDemo: 示例
GitHub - HeBianGu/WPF-ControlBase: Wpf封装的自定义控件资源库
GitHub - HeBianGu/WPF-Control: WPF轻量控件和皮肤库
七、了解更多
System.Windows.Controls 命名空间 | Microsoft Learn