simonalexander2005 simonalexander2005 - 2 years ago 110 Question

How to edit data in a binding to a custom ConfigurationElementCollection

I am using a custom

, which
Implements INotifyCollectionChanged
. Each of the elements that can be stored inside the collection (all of which inherit
), also
Implements INotifyPropertyChanged

I have a config handler class that stores the collection in a property (
), when its constructor is called. This
Implements INotifyPropertyChanged

The constructor is as follows:

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

I can bind to CustomCollection just fine:

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

And this displays all the elements onscreen correctly.

As soon as I try to edit one of the elements, however, I get an exception:

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)

How can I make this binding editable? The only way I can think to do it, is to make some more traditional classes (i.e. not configuration classes) and copy all the data into those - but that seems like a waste when I've already got all the observable properties I need set up.

Answer Source

Is your collection an IEnumerable<ConfigurationElement>? Enumerables cannot be edited in the DataGrid. Convert it to a List<ConfigurationElement>

ConfigurationElementCollection seems to be an IEnumerable. From msdn:

public abstract class ConfigurationElementCollection : ConfigurationElement, 
    ICollection, IEnumerable

You should make your class a List:

CustomCollection = (from ConfigurationElement ce in someConfigurationElementCollection select ce).ToList();
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download