马上注册,结交更多好友,享用更多功能,让你轻松玩转社区。
您需要 登录 才可以下载或查看,没有账号?立即注册
×
- 代码经常碰到范例A转换到范例C,但是已经写好范例A转换到范例B、范例B转换范例C。通常碰到这种环境,通常会重新写过一个转换器来举行满足需求。以下是办理该痛点。
- /// <summary>
- /// 转换器组转换器
- /// </summary>
- [ContentProperty(nameof(Converters))]
- public class ValueConverterGroup : IValueConverter
- {
- public List<IValueConverter> Converters { get; set; } = new List<IValueConverter>();
- public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
- {
- if (this.Converters is IEnumerable<IValueConverter> converters)
- {
- return converters.Aggregate(value, (current, converter) => converter.Convert(current, targetType, parameter, culture));
- }
- return DependencyProperty.UnsetValue;
- }
- public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
- {
- if (this.Converters is IEnumerable<IValueConverter> converters)
- {
- return converters.Reverse().Aggregate(value, (current, converter) => converter.ConvertBack(current, targetType, parameter, culture));
- }
- return DependencyProperty.UnsetValue;
- }
- }
复制代码- <local:ValueConverterGroup x:Key="StringToVisibilityConvert">
- <local:StringToUpperConvert />
- <local:StringToVisibilityConvert />
- </local:ValueConverterGroup>
复制代码- public abstract class ValueConverterBase : MarkupExtension, IValueConverter
- {
- public abstract object Convert(object value, Type targetType, object parameter, CultureInfo culture);
- public virtual object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
- {
- return Binding.DoNothing;
- }
- public override object ProvideValue(IServiceProvider serviceProvider)
- {
- return this;
- }
- }
复制代码 使用该类封装StringToUpperConvert- //使用: <TextBlock Text="{Binding TestText, Mode=OneWay, UpdateSourceTrigger=PropertyChanged, Converter={local:StringToUpperConvert}}" />
- public class StringToUpperConvert : ValueConverterBase
- {
- public override object Convert(object value, Type targetType, object parameter, CultureInfo culture)
- {
- if (value is not null && value is string)
- {
- return ((string)value).ToUpper();
- }
- return Binding.DoNothing;
- }
- }
复制代码 3.转换器单例- //使用:<TextBlock Text="{Binding TestText, Converter={x:Static local:StringToUpperConvert.Instance}}" />
- public class StringToUpperConvert : IValueConverter
- {
- public static StringToUpperConvert Instance { get;set; } = new StringToUpperConvert();
- public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
- {
- if (value is not null && value is string)
- {
- return ((string)value).ToUpper();
- }
- return Binding.DoNothing;
- }
- public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
- {
- return DependencyProperty.UnsetValue;
- }
- }
复制代码 |