How to create a custom WPF collection?

I am trying to create my own set of classes that can be added to a WPF control through XAML.

The problem I encountered is adding items to the collection. Here is what I still have.

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 { ... }

And XAML.

<l:MyControl>
    <l:MyControl.MyCollection>
        <l:MyCollection>
            <l:MyItem />
        </l:MyCollection>
    </l:MyControl.MyCollection>
</l:MyControl>

The exception is:
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'.

Does anyone know how I can fix this? Thanks

+3
source share
2 answers

After more searches, I found this blog that had the same error message. It seems I need to implement IList.

public class MyCollection : MyCollectionBase,  IList
{
    // IList implementation...
}
+3
source

, ItemCollection MyCollection Items? XAML . ( XAML, ). :

[ContentProperty("Items")]
public class MyCollection : MyCollectionBase
{
    public ObservableCollection<object> Items { get; private set; }

    public MyCollection()
    {
         Items = new ObservableCollection<object>();
    }
}
+1

Source: https://habr.com/ru/post/1712734/


All Articles