IMul​​tiConverter的默认值是什么?

时间:2016-06-24 16:17:57

标签: c# wpf windows .net-4.5

背景...

我有这个代码每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时,它不会造成任何伤害?

2 个答案:

答案 0 :(得分:1)

Binding.DoNothing是你实际上没有价值的回报。

ConvertBack中你应该抛出NotSupportedException,因为这个转换器没有反函数。您必须确保永远不会通过BindingMode=OneWay之类的方式调用此方法。

答案 1 :(得分:0)

根据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();
}