我正在尝试创建一组可以通过 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>
异常(exception)情况是:
发生 System.Windows.Markup.XamlParseException
Message="'MyItem' 对象不能添加到'MyCollection'。类型'CollectionTest.MyItem' 的对象不能转换为类型'System.Windows.Controls.ItemCollection'。
有人知道我该如何解决这个问题吗?谢谢
最佳答案
经过更多谷歌搜索,我找到了 this有相同错误消息的博客。看来我也需要实现 IList。
public class MyCollection : MyCollectionBase, IList
{
// IList implementation...
}
关于.net - 如何制作自定义 WPF 集合?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1134986/