C # Winforms Designer: how to copy and paste collections during development?

Suppose I created the following custom control:

public class BookshelfControl : Control
{
    [Editor(typeof(ArrayEditor), typeof(UITypeEditor)),
        DesignerSerializationVisibility(DesignerSerializationVisibility.Content)]
    public Book[] Books { get; set; }

    ...
}

where Bookis a simple user class defined as:

public class Book : Component
{
    public string Author { get; set; }
    public string Genre { get; set; }
    public string Title { get; set; }
}

With this, I can easily edit the collection Booksin the designer of Visual Studio.

However, if I create one instance BookshelfControl, then copy and paste into the constructor, the collection Bookswill not be copied, but instead the second control will refer to all the elements within the first contol collection (for example, bookshelfControl1.Book[0]equal bookshelfControl2.Book[0]).

, : Visual Studio Books ?

+4
2

, , , , .

BookshelfControl, ComponentDesigner.Associated. MSDN:

ComponentDesigner.AssociatedComponents , , .

:

[Designer(typeof(BookshelfControl.Designer))]
public class BookshelfControl : Control
{
    internal class Designer : ControlDesigner
    {
        private IComponent component;

        public override void Initialize(IComponent component)
        {
            base.Initialize(component);
            this.component = component;
        }

        //
        // Critical step getting the designer to 'cache' related object
        // instances to be copied with this BookshelfControl instance:
        //
        public override System.Collections.ICollection AssociatedComponents
        {
            get
            {
                return ((BookshelfControl)this.component).Books;
            }
        }
    }

    [Editor(typeof(ArrayEditor), typeof(UITypeEditor)),
        DesignerSerializationVisibility(DesignerSerializationVisibility.Content)]
    public Book[] Books { get; set; }

    ...
}

AssociatedComponents ( , , ..), , .

, AssociatedComponents , copy (.. CTRL + C) .

, , , !

+1

, . Book Component. :

    [Serializable]
    public class Book 
    {

        public string Author { get; set; }

        public string Genre { get; set; }

        public string Title { get; set; }
    }

, . Component, EditorAttribute.

+1

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


All Articles