0

我正在使用自定義ConfigurationElementCollection,其中Implements INotifyCollectionChanged。可以存儲在集合中的每個元素(所有這些元素都繼承ConfigurationElement),也可以是Implements INotifyPropertyChanged如何編輯綁定到自定義ConfigurationElementCollection的數據

我有一個配置處理程序類,它將集合存儲在屬性(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) 
    ... 

我怎樣才能使這種結合可編輯的?我認爲這樣做的唯一方法是創建一些更傳統的類(即不是配置類)並將所有數據複製到這些類中 - 但是當我已經獲得了所有需要設置的可觀察屬性時,這看起來很浪費向上。

回答

1

您的收藏是IEnumerable<ConfigurationElement>?枚舉數不能在DataGrid中編輯。將其轉換爲List<ConfigurationElement>

ConfigurationElementCollection似乎是IEnumerable。從MSDN:

public abstract class ConfigurationElementCollection : ConfigurationElement, 
    ICollection, IEnumerable 

你應該讓你的類List

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

不,它延伸'ConfigurationElementCollection'一類 - https://msdn.microsoft.com/en-us/library /system.configuration.configurationelementcollection(v=vs.110).aspx – simonalexander2005

+0

@ simonalexander2005它似乎是IEnumerable,我編輯了我的答案。 – Natxo

+0

因此,基於我必須使用'ConfigurationElementCollection'類的事實,這是一個簡單的例子嗎?實現細節隱藏在'ConfigurationElementCollection'類中,所以我該怎麼做? – simonalexander2005

相關問題