强制 WPF DataGrid 添加特定新项目的最佳方法是什么?

Mic*_*zyk 3 wpf datagrid datacontract itemssource type-constraints

DataGrid在 WPF 应用程序中有ItemsSource一个我编写的自定义集合。该集合强制其所有项目满足某个要求(即它们必须介于某个最小值和最大值之间)。

集合的类签名是:

   public class CheckedObservableCollection<T> : IList<T>, ICollection<T>, IList, ICollection,
                                            INotifyCollectionChanged
                                             where T : IComparable<T>, IEditableObject, ICloneable, INotifyPropertyChanged
Run Code Online (Sandbox Code Playgroud)

我希望能够使用这样的DataGrid功能,即在DataGrid结果的最后一行提交编辑,将新项目添加到ItemsSource.

Unfortunately the DataGrid simply adds a new item created using the default constructor. So, when adding a new item, DataGrid indirectly (through its ItemCollection which is a sealed class) declares:

ItemsSource.Add(new T())
Run Code Online (Sandbox Code Playgroud)

where T is the type of elements in the CheckedObservableCollection. I would like for the grid to instead add a different T, one that satisfies the constraints imposed on the collection.

My questions are: Is there a built in way to do this? Has somebody done this already? What's the best (easiest, fastest to code; performance is not an issue) way to do this?

Currently I just derived DataGrid to override the OnExecutedBeginEdit function with my own as follows:

public class CheckedDataGrid<T> : DataGrid where T : IEditableObject, IComparable<T>, INotifyPropertyChanged, ICloneable
{
  public CheckedDataGrid() : base() { }

  private IEditableCollectionView EditableItems {
     get { return (IEditableCollectionView)Items; }
  }

  protected override void OnExecutedBeginEdit(ExecutedRoutedEventArgs e) {
     try {
        base.OnExecutedBeginEdit(e);
     } catch (ArgumentException) {
        var source = ItemsSource as CheckedObservableCollection<T>;
        source.Add((T)source.MinValue.Clone());
        this.Focus();
     }
  }
}
Run Code Online (Sandbox Code Playgroud)

Where MinValue is the smallest allowable item in the collection.

I do not like this solution. If any of you have advice I would be very appreciative!

Thanks

Gre*_*Ros 5

这个问题是现在下半解4.5使用AddingNewItem的事件DataGrid这是我对类似问题的回答

我通过使用 DataGrid 的AddingNewItem事件解决了这个问题。这个几乎完全没有记录的事件不仅告诉您正在添加新项目,而且 [允许您选择要添加的项目][2]。AddingNewItem在其他任何事情之前开火;的NewItem属性EventArgs很简单null

即使您为事件提供了处理程序,如果该类没有默认构造函数,DataGrid 也将拒绝允许用户添加行。然而,奇怪的是(但值得庆幸的是)如果你有一个,并设置了 的NewItem属性AddingNewItemEventArgs,它将永远不会被调用。

如果您选择这样做,您可以使用诸如[Obsolete("Error", true)]和之类的属性[EditorBrowsable(EditorBrowsableState.Never)]来确保没有人会调用构造函数。您还可以让构造函数体抛出异常

反编译控件让我们看看那里发生了什么......