【发布时间】:2014-09-06 04:57:23
【问题描述】:
我有一个ComboBox,它的ItemsSource 绑定到一个ObservableCollection<CustomObject>,其中CustomObject 有一些属性。
示例类:
public class CustomObject : INotifyPropertyChanged
{
public string Property1 { /*...omitted for brevity...*/ }
public string Property2 { /*...omitted for brevity...*/ }
public string Property3 { /*...omitted for brevity...*/ }
}
我的ComboBox 的SelectedItem 属性绑定到出现在DataGrid 行中的CustomObject 属性。
示例类:
public class DataGridEntry : INotifyPropertyChanged
{
public CustomObject Column1 { /*...omitted for brevity...*/ }
public string Column2 { /*...omitted for brevity...*/ }
public string Column3 { /*...omitted for brevity...*/ }
}
我在窗口初始化期间创建了ObservableCollection<CustomObject>,然后将DataGrid 的数据上下文设置为ObservableCollection<DataGridEntry>。
我的目标是将初始值加载到我的DataGrid 中,但我不知道如何使ComboBox 意识到指定的CustomObject 可以在其ItemsSource 中找到,因此,@987654338 @ 不会呈现 SelectedItem。
这是我加载初始值的方式:
ObservableCollection<DataGridEntry> entries = new ObservableCollection<DataGridEntry>();
MyWindow.DataContext = this;
entries.Add(new DataGridEntry(new CustomObject("val1", "val2", "val3"), "col2", "col3");
你知道我是如何让ComboBox 设置它的SelectedItem 属性的吗?如果我更改我的代码以使DataGridEntry 仅适用于string 属性,那么ComboBox 在按我预期的初始化后呈现SelectedItem。但是对于引用类型,它不起作用。
如果需要,这就是我将数据绑定到
Combobox 的方式:
<ComboBox ItemsSource="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type Window}}, Path=DataContext.CustomObjectsCollection}" SelectedItem="{Binding Column1, UpdateSourceTrigger=PropertyChanged}"/>
编辑:
如果不清楚,ObservableCollection<CustomObject> 包含一个与上面相同的元素:new CustomObject("val1", "val2", "val3");
我怀疑ComboBox 没有意识到这两个CustomObjects 是等价的。由于这种怀疑,我为CustomObject 覆盖了Equals 和GetHashCode 函数,但没有成功。显然,ComboBox 在检测非引用数据类型(如字符串)的相等性时没有问题。
谢谢您的帮助! :)
【问题讨论】:
-
分配 DataContext 时的“this”是什么?它应该非常简单:创建一个 ViewModel,它包含一个集合 ObservableCollection
和一个 ObservableCollection 。接下来,将 ComboBox ItemsSource 绑定到 CustomObjects 的集合,并将其 SelectedItem 绑定到 DataGrid 的 SelectedItem.Column1(其中 Column1 是 CustomObject)。最后,将 DataGrid 的 ItemsSource 设置为 DataGridEntries 的集合。当然......你知道你可以在你的数据网格中放置一个 ComboBox inside 对吧? -
为简单起见,我省略了我的
DataContext。实际上,我有一个包装类,它将这些集合作为属性保存。我将主窗口的DataContext设置为指向该包装器的一个实例。我相信问题在于添加到DataGridEntry的CustomObject和集合中相应的CustomObject的相等性。我想我忘了提到ObservableCollection<CustomObject>包含一个CustomObject,它与插入DataGrid的那个相同:new CustomObject("val1", "val2", "val3") -
具有相同值的 CustomObjects 实际上是同一个对象似乎会更好?
标签: c# wpf datagrid combobox observablecollection