我想創建一個自定義的類集,可以通過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