IMultiConverter的默认值是多少

本文关键字:多少 默认值 IMultiConverter | 更新日期: 2023-09-27 17:49:15

背景

我有这样的代码,它每4个月崩溃一次整个应用程序。

崩溃发生在ConvertBack函数中(根据堆栈跟踪(:

public enum MultiBoolConverterType
{
    And,
    Or,
}
public class MultiBoolConverter : IMultiValueConverter
{
    public MultiBoolConverterType ConverterType { get; set; }
    public object Convert(object[] values, Type targetType, object parameter, CultureInfo culture)
    {
        var booleans = values.OfType<bool>();
        switch (ConverterType)
        {
            case MultiBoolConverterType.And:
                return booleans.All(b => b);
            case MultiBoolConverterType.Or:
                return booleans.Any(b => b);
            default:
                throw new ArgumentOutOfRangeException();
        }
    }
    public object[] ConvertBack(object value, Type[] targetTypes, object parameter, CultureInfo culture)
    {
        throw new NotImplementedException();
    }
}

问题

我用什么来替换throw new NotImplementedException();,以确保如果无意中调用了ConvertBack,它不会造成危害?

IMultiConverter的默认值是多少

Binding.DoNothing是在实际没有值的情况下返回的值。

ConvertBack中,应该抛出NotSupportedException,因为这个转换器没有反函数。你必须确保这永远不会被称为你自己,通过BindingMode=OneWay等。

根据H.B.的注释,返回一个Binding.DoNothing:数组

public object[] ConvertBack(object value, Type[] targetTypes, object parameter, CultureInfo culture)
{
    _log.Warn("Warning. Reverse binding on MultiBoolConverter called. Prevent this by using OneWay.");
    List<object> result = new List<object>();
    foreach(var t in targetTypes)
    {
        result.Add(Binding.DoNothing);
    }
    return result.ToArray();
}