0

I created a C# class that extends Button, but associates a generic type like this:

public class DropButton<T> : Button where T : INamed
{
    //contains lots of properties and methods that
    //reference and operate on the objects of type T
}

...where INamed interface specifies what properties any class should have to be used with my DropButton:

public interface INamed
{
    string Name { get; set; }
    bool Selected { get; set; }
}

I can add an instance of the control on a WinForms form programmatically:

private DropButton<MySet> MyDropButton = new DropButton<MySet>();
//Then set properties of the control in the form constructor and add it.

It works splendidly and it keeps my form code a lot cleaner.

However, the new control does not show up in the Toolbox for the project. Nor does the designer recognize the code if I manually modify the .Designer.cs file with an instance of it.

So two questions:

  1. Is there a way to trick the WinForms form designer to allow it in design mode?
  2. Is there a better way to go about this pattern?
John Kurtz
  • 775
  • 8
  • 16
  • Does this help? https://stackoverflow.com/questions/8931328 – D Stanley Sep 28 '22 at 20:38
  • @DStanley I checked and the "Tools/Options/Windows Forms Designer/Automatically Populate Toolbox" settting was true. I think it does not know how to handle the . – John Kurtz Sep 28 '22 at 20:59
  • 2
    If you were to drop a `DropButton` on your form from the toolbox, where would the T come from? The properties in the designer are all instance properties. I can't imagine where T could be specified. – Flydog57 Sep 28 '22 at 21:16
  • @Flydog57 Yes, that is the dilemma. I'd be delighted if Visual Studio asked me for the class to use for T :) As a workaround, I use a regular button as a placeholder and then I programmatically replace it in the form constructor by passing the button instance to a method in my DropButton class. It copies the properties from the template button to the DropButton and then takes its place on the form. – John Kurtz Sep 28 '22 at 21:28
  • 2
    You can to the same thing you're doing in code, provide a definition of `T`. I.e., create a class derived from your `DropButton` as, e.g., `public class DropButtonImpl : DropButton { public DropButtonImpl() { } // etc. }`. This derived class can be added to the ToolBox, since the Type of `T` is now known – Jimi Sep 28 '22 at 21:28
  • @Jimi Splendid Idea! It worked. Similarly, it is very little extra code to create a variety of DropButtons...DropButton4Set, DropButton4PicShow, DropButton4VidShow, DropButton4WebShow, and so on, explicitly for each object type. Sometimes you just need need someone to stop the Ferris wheel and help you off :) – John Kurtz Sep 28 '22 at 21:56

0 Answers0