【发布时间】:2009-07-16 01:25:52
【问题描述】:
我正在尝试创建一组可以通过 XAML 添加到 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 样式接口,因为它们支持可覆盖的添加/删除功能。我知道这不是对您问题的直接回答,但想知道是否有理由不这样做?
标签: .net wpf xaml collections