我想创建一个自定义的类集,可以通过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'.
任何一个人知道如何解决这个问题?谢谢
您是否可以从System.Collections.ObjectModel中的一个以DOM为中心的集合类继承基类?这些类(例如Collection,KeyedCollection等)非常适合创建DOM风格的接口,因为它们支持可覆盖的添加/删除功能。我知道这不是对你的问题的直接回应,但想知道是否有某种理由不这样做? – Adrian 2009-07-16 03:40:17