Search code examples
imagevisual-studiouser-controlsresourcespropertygrid

Add resource/import image to custom UserControl attribute in VS Designer via Dialog(s)


My aim is to create a custom control displaying some images, which can be added/exchanged by the user of that control. So, if it is added to a Form, the GUI designer should be able to change some or all images provided by the control editing the appropriate attribute.

In my Test-Project I have a simple control with 4 Attributes:

 public Image MyImage { get; set; } = null;
 public List<int> MyListOfInt { get; set; } = new List<int>();
 public List<Image> MyListOfImages { get; set; } = new List<Image>();
 public ImageList MyImageList { get; set; } = new ImageList();

Using this control in a Windows Form Project, clicking on

  1. MyImage brings up the 'Select resource' dialog. OK

  2. MyListOfInt brings up the 'Int32 Collection Editor' dialog. OK

  3. MyListOfImages brings up the 'Image Collection Editor' dialog, but using 'Add' button shows message:

    'Cannot create an instance of System.Drawing.Image because it is an abstract class.'

  4. MyImageList shows an emtpy list, which cannot be edited.

My question is, if it's possible to tell VS Designer to use the 'Select resource' dialog when clicking 'Add' button and what needs to be done?


Solution

  • I've got another answer from MSDN: How to edit UserControl attribute of type ImageList in Designer PropertyGrid (add/remove/exchange images)

    I will describe the idea in short. First create a new control with an ImageList attribute.

    public partial class NewControl : UserControl {
        public NewControl() {
            InitializeComponent();
        }
    
        public ImageList MyImageList { get; set; } = null;
    }
    
    1. Then drag this control on any form.
    2. Additionally drag an ImageList control from Toolbox onto this form - I called it 'MyImages'.
    3. Edit MyImages → Images with designer.
    4. Assign 'MyImages' to NewControl's instance attribute MyImageList in property grid

    Edit MyImages

    The only drawback I see here is, that if the control already has an initialized ImageList attribute, the designer cannot handle it. If you try to edit MyImageList before you assigned another list, the designer shows the controls default list, that comes with the control. But it's not possible to edit that list.

    This solution is much easier to deal with and much shorter than the first solution above, so that I prefer it more.