ComboBox MultiBinding如何绑定到SelectedItem的属性

问题描述

我正在将 MultiBinding 用于组合框。我要绑定的参数之一是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加载时被命中,而在我选择一个项目后将不会被命中。

解决方法

您应该检查您的string方法中是否获得了Convert

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;:

    //...
}

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