【问题标题】:How does ComboBox MultiBinding bind to SelectedItem's propertyComboBox MultiBinding如何绑定到SelectedItem的属性
【发布时间】:2021-02-15 17:14:39
【问题描述】:

我将 MultiBinding 用于 ComboBox。我要绑定的参数之一是SelectedItem's SelectedName。这里SelectedNamestring 类型。

如果不是 MultiBinding,我有这个效果很好:

<ComboBox Background="{Binding SelectedItem.SelectedName, 
        RelativeSource={RelativeSource Self}, Converter={StaticResource MyConverter}}">

但是在 MultiBinding 中,当我尝试绑定到 SelectedItem.SelectedName 时,它会报告

无法将“MS.Internal.NamedObject”类型的对象转换为类型 'System.String'。

这是我的代码:

<ComboBox.Background>
    <MultiBinding Converter="{StaticResource MyMultiBindingConverter}">
        <Binding .../>
        <Binding RelativeSource="{RelativeSource Self}" Path="SelectedItem.SelectedName"/> //this line fails
    </MultiBinding>
</ComboBox.Background>

我怎样才能使它正确?谢谢。

更新信息:

ComboBox 没有默认的SelectedItem。当我使用MyConverter时,如果我没有选择一个项目,Convert方法中的断点将不会被命中。在我选择一个项目后,断点被击中,这是我想要的行为。

但是,当我使用MyMultiBindingConverter 时,情况完全相反 - 断点将在 UI 加载时被命中,而在我选择一个项目后不会被命中。

【问题讨论】:

  • 我相信MultiBinding 标记中的上下文不是您所期望的。 {Relative Source Self} 不会解析为 ComboBox 对象。您可能应该改用RelativeAncestor。请参阅建议的副本。
  • 你好@Peter Duniho。我修改为&lt;Binding RelativeSource="{RelativeSource AncestorType=ComboBox}" Path="SelectedItem.SelectedName"/&gt;,还是一样的错误,我应该把DataContext放在某个地方吗?
  • 似乎{Relative Source Self} 没问题 - 与“SingleBinding”的唯一区别是Convert 方法中的断点将在 UI 加载时被命中(虽然我不知道是什么导致了这种差异) .我修改转换器后,它工作正常。

标签: wpf multibinding


【解决方案1】:

你应该检查你的Convert方法中是否有string

public object Convert(object[] values, Type targetType, object parameter, CultureInfo culture)
{
    if (values.Length < 2)
        return Binding.DoNothing;

    string selectedName = values[1] as string;
    if (string.IsNullOrEmpty(selectedName))
        return Binding.DoNothing;:

    //...
}

您不能假定每次调用Convert 方法时SelectedItem.SelectedName 属性都会返回一个值。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-09-29
    • 1970-01-01
    • 2014-12-08
    • 1970-01-01
    • 1970-01-01
    • 2010-10-24
    • 1970-01-01
    相关资源
    最近更新 更多