2

如果我使用IValueConverter它可以工作,而IMultiValueConverter返回相同的值却不能,这是为什么呢?

<Border Background="Red" Width="100" Height="100"
        CornerRadius="{Binding Converter={vc:SingleAndMultiConverter}}" />
<Border Background="Red" Width="100" Height="100"
        CornerRadius="{MultiBinding Converter={vc:SingleAndMultiConverter}}" />
public class SingleAndMultiConverter : MarkupExtension, IValueConverter, IMultiValueConverter
{
    public override object ProvideValue(IServiceProvider serviceProvider)
    {
        return this;
    }

    public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        return Convert();
    }
    public object Convert(object[] values, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        return Convert();
    }
    private object Convert()
    {
        return 15;
    }

    public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        throw new NotSupportedException();
    }
    public object[] ConvertBack(object value, Type[] targetTypes, object parameter, System.Globalization.CultureInfo culture)
    {
        throw new NotSupportedException();
    }
}

多重绑定会引发此错误:

BindingExpression 产生的值对目标属性无效。值='15'

4

2 回答 2

2

Border.CornerRadius是类型CornerRadius。值转换器应始终为属性返回正确的类型。

很难说为什么它们的行为不同,大概是因为某些无法解释的原因在使用多重绑定时没有使用类型转换器进行默认值转换。如果您深入研究源代码,您可能会发现一些东西,但这可能不会是一次愉快的旅程。

于 2012-03-03T20:03:04.143 回答
0

HB 说了什么 +1

[ValueConversion(typeof(object[]),typeof(CornerRadius))]
public class Multi : IMultiValueConverter
{
    public object Convert(object[] values, Type targetType, object parameter, CultureInfo culture)
    {
        return new CornerRadius(Double.Parse("15"));
    }

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

}
于 2012-03-03T20:58:46.440 回答