.net - 如何制作自定义 WPF 集合?

标签 .net wpf xaml collections

我正在尝试创建一组可以通过 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/

相关文章:

c# - 在 cors 主机中设置时,是否需要在 C# 中定义协议(protocol)

c# - System.Timers.Timer 仅提供每秒最多 64 帧

c# - 更改 GridView 标题高度

c# - 将对象转换为列表<String>

c# - 如何从 BackgroundWorker 线程中更新标签?

wpf - 将 IGrouping 绑定(bind)到功能区组

c# - 警报不起作用,这有什么问题

.NET 配置部分设计器 - 我的集合在哪里?

WPF ComboBox 绑定(bind)行为

c# - 交替背景颜色网格行不起作用