本文介绍了具有ObservableCollection< ComboBoxItem>的相同ItemsSource的两个组合框;的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

<ComboBox Grid.Row="0" ItemsSource="{Binding Path=optList}" IsSynchronizedWithCurrentItem="False" />
<ComboBox Grid.Row="1" ItemsSource="{Binding Path=optList}" IsSynchronizedWithCurrentItem="False" />
public ObservableCollection<ComboBoxItem> optList{ get; set; } = new ObservableCollection<ComboBoxItem>() {
new ComboBoxItem() { Content = "1"},
new ComboBoxItem() { Content = "2"}
}

当我在组合框之间切换时,一个下拉列表变为空。你知道为什么吗?

When I am switching between comboboxes then one dropdown become empty. Do you know why? It is working with collection of String.

推荐答案

ComboBoxItem是一个FrameworkElement,不能属于多个父级。

ComboBoxItem is a FrameworkElement which cannot belong to multiple parents.

使用字符串收集时,每个ComboBox都会为同一字符串生成一个新的ComboBoxItem。当集合包含ComboBoxItems时,comboBoxes 不要创建其他ComboBoxItems并重用现有的ComboBoxItems,将它们相互窃取。

When you use string collection, each ComboBox generate a new ComboBoxItem for the same string. When collection contains ComboBoxItems, comboBoxes don't create other ComboBoxItems and reuse existing, stealing them from each other.

此外,当您遵循MVVM方法时,则在提供绑定源的视图模型中不应包含ComboBoxItem对象。

Additionally when you follow MVVM approach, you should not have ComboBoxItem objects in a view model which provides binding source.

因此字符串集合是正确的解决方案。

So string collection is a correct solution.

这篇关于具有ObservableCollection&lt; ComboBoxItem&gt;的相同ItemsSource的两个组合框;的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-29 11:49