【发布时间】:2021-02-15 17:14:39
【问题描述】:
我将 MultiBinding 用于 ComboBox。我要绑定的参数之一是SelectedItem's SelectedName。这里SelectedName 是string 类型。
如果不是 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。我修改为
<Binding RelativeSource="{RelativeSource AncestorType=ComboBox}" Path="SelectedItem.SelectedName"/>,还是一样的错误,我应该把DataContext放在某个地方吗? -
似乎
{Relative Source Self}没问题 - 与“SingleBinding”的唯一区别是Convert方法中的断点将在 UI 加载时被命中(虽然我不知道是什么导致了这种差异) .我修改转换器后,它工作正常。
标签: wpf multibinding