2009-07-16 88 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