문제

What is the difference between using a Converter (IValueConverter) and passing in other values as parameters (ConverterParameter) vs using a MultiConverter (IMultiValueConverter) and just passing in multiple converter values?

도움이 되었습니까?

해결책

There are two main differences. One is that ConverterParameter is not a Binding and does not listen for property changes, so the Binding won't refresh automatically if the value changes.

The other difference is that the ConverterParameter is an input to both Convert and ConvertBack, while all of the Bindings in a MultiBinding are inputs to Convert and outputs of ConvertBack. For example, if you are converting from DateTime to string, you might have the ConverterParameter be a format string, since that affects the conversion in both directions:

public class DateTimeConverter
    : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
    {
        return ((DateTime)value).ToString((string)parameter, null);
    }

    public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
    {
        return DateTime.ParseExact((string)value, (string)parameter, null);
    }
}

On the other hand, if you want to convert from two doubles to a Size, then you would want to return two doubles when converting back:

public class SizeConverter
    : IMultiValueConverter
{
    public object Convert(object[] values, Type targetType, object parameter, CultureInfo culture)
    {
        return new Size((double)values[0], (double)values[1]);
    }

    public object[] ConvertBack(object value, Type[] targetTypes, object parameter, CultureInfo culture)
    {
        var size = (Size)value;
        return new object[] { size.Width, size.Height };
    }
}
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top