2014-02-24 31 views
2

我有一個用戶控件,該控件的屬性是自定義對象類型的列表。當我從名單<>繼承創建一個自定義類,它主要作品:創建使用CollectionEditor的自定義IList類

public class CustomCol : List<CustomItem> { 
    // ... 
} 

我就能夠實現在用戶控制像這樣的屬性:

CustomCol _items = new CustomCol(); 
[DesignerSerializationVisibility(DesignerSerializationVisibility.Content)] 
public CustomCol Items 
{ 
    get { return _items; } 
} 

這使得它的行爲與我預期的一樣。我可以單擊Designer中的省略號按鈕,它將調出CollectionEditor,並正確添加項目添加CustomItems。

不幸的是,這種方法不允許我檢測CollectionEditor中的項目何時添加,刪除或修改。經過大量研究後,我發現這是因爲設計師編輯調用IList.Add()來添加新項目,並且這是不可覆蓋的,所以如果沒有實現自己實現IList的集合類,我將無法攔截這些調用。

所以這正是我試圖做的。我試過的代碼看起來像這樣:

public class CustomCol: System.Collections.IList 
{ 
    private List<CustomItem> = new List<CustomItem>(); 

    int System.Collections.IList.Add(Object value) 
    { 
     _items.Add((CustomItem)value); 
     return _items.Count; 
    } 

    // All of the other IList methods are similarly implemented. 
} 

在繼續之前,我已經看到一個問題。 CollectionEditor將傳遞通用的System.Objects,而不是我的CustomItem類。

所以,我想未來的事情正在實施的IList代替,因爲這樣的:

public class CustomCol: IList<CustomClass> 
{ 
    private List<CustomItem> = new List<CustomItem>(); 

    void ICollection<CustomItem>.Add(NameValueItem item) 
    { 
     _items.Add(item); 
    } 

    // All of the other IList methods are similarly implemented. 
} 

從理論上講,這個工作,但我不能讓CollectionEditor在設計師都推出。我一整天都在努力研究這個問題,在網上尋找解決方案,嘗試試着瞭解所有這些工作。在這一點上,我有一個非常嚴重的頭痛,並且正在尋找任何指導。總結:我想創建一個用戶控件,該屬性是一個自定義集合類,我可以在設計器中使用集合編輯器(或類似的東西)進行編輯,我需要知道這些設計器更改是如何進行的我可以更新控件的外觀。

+0

實現'ITypedList','IBindingList',和/或'IListSource'(這樣你就可以實現在一個單獨的類中的另兩個) – SLaks

回答

1

您可以按照框架集合的方式實現您的自定義集合。不要看太多。

照常執行非泛型IList,但使實現的方法保密。然後爲每個實現的方法添加另一個公共方法,但是這次這些公共方法將接受所需的自定義類型。這些方法將通過類型轉換從實現的私有方法中調用。

這是框架集合遵循的方式。看看UIElementCollection課程。你會看到完全相同的實現。

IList.Add方法的示例: 假設自定義類名爲TextElement

private int IList.Add(object value) 
{ 
    return Add((TextElement)value); 
} 

public int Add(TextElement element) 
{ 
    [Your custom logic here] 
} 

編輯: 你不能只是含蓄地實現使用的私有方法的接口。你必須明確地做到這一點。例如,您需要執行private int IList.Add而不是private int Addprivate void ICollection.CopyTo而不是private void CopyTo以使所有這些工作。

相關問題