我已经找到了适合我的情况的解决方案。我从上面提供的链接下载了自定义多列ComboBox和DataGridComboBoxColumn子类,然后将其与Entity Framework Code-First POCOs配合使用,这解决了我的问题。以下是我使用POCOs使其正常工作所需进行的修改。
在CustDataGridComboBoxColumn中,有几个重写方法。您只需要稍微修改以下两个重写方法即可。由于不知道控件的属性,我使用反射来设置该属性。
原始实现通过使用SelectedValuePath从DataRowView获取正确的行来完成此操作。
protected override object PrepareCellForEdit(FrameworkElement editingElement, RoutedEventArgs editingEventArgs)
{
DataGridCell cell = editingEventArgs.Source as DataGridCell;
if (cell != null)
{
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)
{
PropertyInfo info = editingElement.DataContext.GetType().GetProperty(“YourPropertyName”, BindingFlags.Public | BindingFlags.Instance);
info.SetValue(editingElement.DataContext, comboBox.SelectedValue, null);
return true;
}
此外,如果您打算完全使用代码动态创建此自定义控件而不是在XAML中创建,则必须向Columns属性添加一个setter,因为默认情况下它是只读的。
[DesignerSerializationVisibility(DesignerSerializationVisibility.Content)]
public ObservableCollection<DataGridTextColumn> Columns
{
get
{
if (this.columns == null)
{
this.columns = new ObservableCollection<DataGridTextColumn>();
}
return this.columns;
}
set
{
this.columns = value;
}
}
感谢提供的意见和答案。抱歉一开始没有能够准确表达问题。