我找到了适合我的特定场景的解决方案。我从上面上次更新中的链接下载了包含 DataGridComboBoxColumn 子类的自定义多列 ComboBox。基本上我只是使用 Entity Framework Code-First POCO 完成了这项工作,它解决了我的问题。这是我必须做的才能使它与 POCO 一起工作。
在 CustDataGridComboBoxColumn 内部有一些覆盖。您只需要稍微修改以下两个覆盖。我正在使用反射来更改设置属性,因为我不知道它将来自控件。
最初的实现是通过使用 SelectedValuePath 从 DataRowView 中获取正确的 Row 来实现的。
protected override object PrepareCellForEdit(FrameworkElement editingElement, RoutedEventArgs editingEventArgs)
{
DataGridCell cell = editingEventArgs.Source as DataGridCell;
if (cell != null)
{
// Changed to support EF POCOs
PropertyInfo info = editingElement.DataContext.GetType().GetProperty("YourPropertyName", BindingFlags.Public | BindingFlags.Instance);
object obj = info.GetValue(editingElement.DataContext, null);
comboBox.SelectedValue = obj;
}
return comboBox.SelectedItem;
}
protected override bool CommitCellEdit(FrameworkElement editingElement)
{
// Dynamically set the item on our POCO (the DataContext).
PropertyInfo info = editingElement.DataContext.GetType().GetProperty(“YourPropertyName”, BindingFlags.Public | BindingFlags.Instance);
info.SetValue(editingElement.DataContext, comboBox.SelectedValue, null);
return true;
}
此外,如果您打算完全在代码中而不是在 XAML 中动态创建此自定义控件,则必须将设置器添加到 Columns 属性,因为默认情况下它设置为只读。
//The property is default and Content property for CustComboBox
[DesignerSerializationVisibility(DesignerSerializationVisibility.Content)]
public ObservableCollection<DataGridTextColumn> Columns
{
get
{
if (this.columns == null)
{
this.columns = new ObservableCollection<DataGridTextColumn>();
}
return this.columns;
}
set
{
this.columns = value;
}
}
感谢您提供的意见和答案。抱歉,我最初无法充分表达这个问题以使其更有意义。