问题描述
我正在将 MultiBinding 用于组合框。我要绑定的参数之一是SelectedItem's Selectedname
。这里的Selectedname
是string
类型。
如果不是 MultiBinding ,我的效果很好:
<ComboBox Background="{Binding SelectedItem.Selectedname,RelativeSource={RelativeSource Self},Converter={StaticResource MyConverter}}">
但是在 MultiBinding 中,当我尝试绑定到SelectedItem.Selectedname
时会报告
这是我的代码:
<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
属性都会返回一个值。