如何编辑绑定到自定义 ConfigurationElementCollection 中的数据

How to edit data in a binding to a custom ConfigurationElementCollection

我正在使用自定义 ConfigurationElementCollectionImplements INotifyCollectionChanged。每个可以存储在集合中的元素(都继承ConfigurationElement),也Implements INotifyPropertyChanged.

我有一个配置处理程序 class,它在调用其构造函数时将集合存储在 属性 (CustomCollection) 中。这个ConfigHandlerImplements INotifyPropertyChanged.

构造函数如下:

 _config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None)
CustomCollection = (DirectCast(_config.GetSection("CustomCollection"), CustomConfigurationSection)).CustomCollection

我可以很好地绑定到 CustomCollection:

 <DataGrid DataContext="{Binding Source={x:Static l:Handlers.ConfigHandler}}" ItemsSource="{Binding Path=CustomCollection}" />

这会正确显示屏幕上的所有元素。

当我尝试编辑其中一个元素时,我得到一个异常:

System.InvalidOperationException: 'EditItem' is not allowed for this view.
    at System.Windows.Controls.ItemCollection.System.ComponentModel.IEditableCollectionView.EditItem(Object item)
    at System.Windows.Controls.DataGrid.EditRowItem(Object rowItem)
    ...

如何使此绑定可编辑?我能想到的唯一方法是制作一些更传统的 classes(即不是配置 classes)并将所有数据复制到那些 - 但当我'我已经获得了我需要设置的所有可观察属性。

你的 collection 是 IEnumerable<ConfigurationElement> 吗?无法在 DataGrid 中编辑枚举。将其转换为 List<ConfigurationElement>

ConfigurationElementCollection 似乎是一个 IEnumerable。来自 msdn:

public abstract class ConfigurationElementCollection : ConfigurationElement, 
    ICollection, IEnumerable

你应该让你的 class 成为 List:

CustomCollection = (from ConfigurationElement ce in someConfigurationElementCollection select ce).ToList();