WPF(继承)

1.IValueConverter 接口

提供将自定义逻辑应用于绑定的方法。 

using System;
using System.Globalization;
using System.IO;
using System.Windows.Data;
using System.Windows.Media.Imaging;
using System.Data;

[ValueConversion(typeof(string), typeof(Enum))]
public class EnumConverter : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
    {
        return System.Convert.ToInt64(value).ToString();
    }

    public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
    {
        return value;
    }
}

 上述转换器实现将枚举转换为其对应的索引值。


using System;
using System.Globalization;
using System.IO;
using System.Windows.Data;
using System.Windows.Media.Imaging;

[ValueConversion(typeof(BitmapImage), typeof(byte[]))]
public class ImageConverter : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
    {
        if (value == null)
        {
            return null;
        }
        byte[] barr = value as byte[];
        if (barr.Length == 0)
        {
            return null;
        }
        BitmapImage bitmap = new BitmapImage();
        bitmap.BeginInit();
        bitmap.StreamSource = new MemoryStream(barr);
        bitmap.EndInit();
        bitmap.Freeze();
        return bitmap;
    }

    public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
    {
        return value;
    }
}

  上述转换器实现将字节数组转换为图片。


using System;
using System.Globalization;
using System.Windows.Data;

[ValueConversion(typeof(DateTime), typeof(string))]
public class DateConverter : IValueConverter
{
    public string Format { get; set; } = "yyyy-MM-dd HH:mm:ss.fff";

    public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
    {
        DateTime dt = (DateTime)value;
        return dt.ToString(Format);
    }

    public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
    {
        return DateTime.Parse(value.ToString());
    }
}

  上述转换器实现将DateTime转换为时间字符串。

2.IMultiValueConverter 接口

提供在 MultiBinding 中应用自定义逻辑的方法。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Globalization;
using System.Windows.Data;

[ValueConversion(typeof(decimal), typeof(decimal[]))]
public class ValueAddConverter : IMultiValueConverter
{
    public object Convert(object[] values, Type targetType, object parameter, CultureInfo culture)
    {
        decimal result = 0;
        foreach (object v in values)
        {
            result += decimal.Parse(v.ToString());
        }
        return result;
    }

    public object[] ConvertBack(object value, Type[] targetTypes, object parameter, CultureInfo culture)
    {
        throw new NotImplementedException();
    }
}

 上述转换器实现多绑定,进行多个值进行累加。

posted @ 2022-04-12 22:45  Bridgebug  阅读(75)  评论(0编辑  收藏  举报