Best practice when not implementing IValueConvert.ConvertBack

前端 未结 4 1590
难免孤独
难免孤独 2020-12-30 19:24

Just wondering what people think is the best practice when implementing an IValueConverter which does not have a meaningfull ConvertBack implementation (or one that is only

4条回答
  •  醉酒成梦
    2020-12-30 20:21

    I agree with @Todd White's answer.

    Additionally, in order to save time, you can implement a base converter class which implements ConvertBack for you so you don't have to implement it every time saving duplicate code.

    Technically, you don't have to override Convert either; But it has to be implemented in ConverterBase since it implements all methods of the IValueConverter interface. In practice, you will be overriding Convert every time and ConvertBack can be ignored most of the time.

    public class ConverterBase : IValueConverter
    {
        public virtual object Convert(object value, Type targetType, object parameter, CultureInfo culture)
        {
            return DependencyProperty.UnsetValue;
        }
        public virtual object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
        {
            return DependencyProperty.UnsetValue;
        }
    }
    
    public class VisibilityConverter : ConverterBase
    {
        public override object Convert(object value, Type targetType, object parameter, CultureInfo culture)
        {
            return ((bool)value ^ (parameter as bool? == true)).ToVisibility();
        }
    }
    

提交回复
热议问题