【问题标题】:Why does my IMultiBindingConverter get an array of strings when used to set TextBox.Text?为什么我的 IMultiBindingConverter 用于设置 TextBox.Text 时会得到一个字符串数组?
【发布时间】:2011-02-25 08:47:21
【问题描述】:

我正在尝试将 MultiBinding 与转换器一起使用,其中子元素也有转换器。

XAML 如下所示:

<TextBlock>
<TextBlock.Text>
    <MultiBinding Converter="{StaticResource localizedMessageConverter}" ConverterParameter="{x:Static res:Resources.RecordsFound}" >
        <Binding Converter="{StaticResource localizedMessageParameterConverter}" ConverterParameter="ALIAS" Path="Alias" Mode="OneWay" />
        <Binding Converter="{StaticResource localizedMessageParameterConverter}" ConverterParameter="COUNT" Path="Count" Mode="OneWay" />
    </MultiBinding>
</TextBlock.Text>

我在这里面临的问题是,每当它与 TextBlock 一起使用来指定 Text 属性时,我的 IMultiValueConverter 实现都会获取字符串的对象集合,而不是 IValueConverter 返回的类。似乎对内部转换器的结果调用了 ToString() 方法并传递给 IMultiValueConverter。如果用于指定 Label 的 Content 属性,则一切正常。

在我看来,框架假设返回类型将是字符串,但为什么呢?我可以在 MultiBinding 中看到这一点,因为它应该产生与 TextBlock.Text 兼容的结果,但为什么 MultiBinding 中的 Bindings 也会出现这种情况?

如果我从内部 Binding 元素中删除转换器,则会返回本机类型。在我的例子中是字符串和整数。

【问题讨论】:

    标签: wpf data-binding ivalueconverter multibinding imultivalueconverter


    【解决方案1】:

    您的本地化MessageParameterConverter 转换器的targetType 参数可能是System.String。这是因为Bindings的target类型继承自MultiBinding,而MultiBinding的targetType是System.String,因为TextBlock.Text是字符串属性。

    类似问题请看以下文章:Multi-Value Converters, Value Converters and the Case of the Wrong Target Type

    根据 Microsoft Connect,此问题已在 WPF 4.0 中得到修复。见:Microsoft Connect

    上述文章还解释了一种解决方法。

    【讨论】:

    • 谢谢,很棒的信息。这就像 WPF 4.0 中的魅力一样——刚刚测试过。正如我在第一篇文章中提到的,在标签内使用它也可以,这是 MS Connect 上针对此问题的建议解决方法。这是因为目标是 Object 而不是 String。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-05-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多