【问题标题】:Binding multiple ComboBoxes to the same ItemsSource causes problems将多个 ComboBoxes 绑定到同一个 ItemsSource 会导致问题
【发布时间】:2014-12-24 06:38:06
【问题描述】:

我有 2 个ComboBoxes,其ItemsSource 绑定到同一个ObservableCollection

public ObservableCollection<MyType> MyTypeCollection { get; set; }

我定义了 2 个不同的 SelectedItem 属性,它们又绑定到正确的 ComboBox

public MyType MySelectedItem1 { get; set; }
public MyType MySelectedItem2 { get; set; }

每当我在 ComboBoxes 之一中选择一个项目时,我的类中定义的两个 SelectedItem 属性都会设置为该选择。 ComboBoxes 也都设置为该值。

这是为什么?

我尝试了几种方法,例如 Mode=OneWay 等,但都不起作用。

这是我的 XAML(针对问题进行了删减):

<ComboBox SelectedItem="{Binding MySelectedItem1}"
          ItemsSource="{Binding MyTypeCollection, Mode=OneWay}"/>

<ComboBox SelectedItem="{Binding MySelectedItem2}"
          ItemsSource="{Binding MyTypeCollection, Mode=OneWay}"/>

【问题讨论】:

  • 您的帖子说您的 Xaml 已“精简”。原始版本是否偶然在组合框中有IsSynchronizedWithCurrentItem="True"?如果是这样,那是你的问题。
  • @MikeStrobel 是的,他们有,从 XAML 中删除它们解决了这个问题。谢谢!

标签: c# wpf binding combobox itemssource


【解决方案1】:

我猜你在两个ComboBox 控件上都有IsSynchronizedWithCurrentItem="True"。从两者中删除它,这应该可以解决您的问题。

设置IsSynchronizedWithCurrentItem="True" 告诉ComboBox 它应该使其SelectedItem 与底层ICollectionView 中的CurrentItem 保持同步。由于您直接绑定到集合而不是集合视图,因此两个组合框都使用默认集合视图,这是跨控件共享的公共实例。当您的一个组合框更新集合视图的选择时,另一个会看到更改并更新自己的选择以匹配它。

【讨论】:

    猜你喜欢
    • 2010-10-19
    • 2016-07-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-05-11
    • 1970-01-01
    • 2016-04-05
    相关资源
    最近更新 更多