2009-07-16 94 views
2

我想創建一個自定義的類集,可以通過XAML添加到WPF控件。如何製作自定義WPF集合?

我遇到的問題是將項目添加到集合中。這是迄今爲止我所擁有的。

public class MyControl : Control 
{ 
    static MyControl() 
    { 
     DefaultStyleKeyProperty.OverrideMetadata(typeof(MyControl), new FrameworkPropertyMetadata(typeof(MyControl))); 
    } 

    public static DependencyProperty MyCollectionProperty = DependencyProperty.Register("MyCollection", typeof(MyCollection), typeof(MyControl)); 
    public MyCollection MyCollection 
    { 
     get { return (MyCollection)GetValue(MyCollectionProperty); } 
     set { SetValue(MyCollectionProperty, value); } 
    } 
} 

public class MyCollectionBase : DependencyObject 
{ 
    // This class is needed for some other things... 
} 

[ContentProperty("Items")] 
public class MyCollection : MyCollectionBase 
{ 
    public ItemCollection Items { get; set; } 
} 

public class MyItem : DependencyObject { ... } 

和XAML。

<l:MyControl> 
    <l:MyControl.MyCollection> 
     <l:MyCollection> 
      <l:MyItem /> 
     </l:MyCollection> 
    </l:MyControl.MyCollection> 
</l:MyControl> 

唯一的例外是:
System.Windows.Markup.XamlParseException occurred Message="'MyItem' object cannot be added to 'MyCollection'. Object of type 'CollectionTest.MyItem' cannot be converted to type 'System.Windows.Controls.ItemCollection'.

任何一個人知道如何解決這個問題?謝謝

+0

您是否可以從System.Collections.ObjectModel中的一個以DOM爲中心的集合類繼承基類?這些類(例如Collection,KeyedCollection等)非常適合創建DOM風格的接口,因爲它們支持可覆蓋的添加/刪除功能。我知道這不是對你的問題的直接回應,但想知道是否有某種理由不這樣做? – Adrian 2009-07-16 03:40:17

回答

3

經過多次搜索後,我發現有this博客,它有相同的錯誤信息。似乎我還需要實施IList。

public class MyCollection : MyCollectionBase, IList 
{ 
    // IList implementation... 
} 
0

您是否忘記在MyCollection的構造函數中創建ItemCollection的實例,並將其分配給Items屬性?爲了讓XAML解析器添加項目,它需要一個現有的集合實例。它不會爲你創建一個新的(儘管它可以讓你在XAML中創建一個,如果集合屬性有一個setter)。所以:

[ContentProperty("Items")] 
public class MyCollection : MyCollectionBase 
{ 
    public ObservableCollection<object> Items { get; private set; } 

    public MyCollection() 
    { 
     Items = new ObservableCollection<object>(); 
    } 
} 
+1

ItemCollection沒有公共屬性。是否有另一種創建它的方法? – 2009-07-16 01:42:16

+0

對不起,我的意思是沒有公共構造函數。 – 2009-07-16 01:46:03

相關問題