How to design reusable context menus?

2019-07-07 01:02发布

I'm developing a WinForms .NET application. I have few context menus which are used on various places including some user controls. There is no ultimate root form which could hold those menus (I could design in those form's designer) on a single place.

I would like to make those menus standalone controls and be able to drop them from Toolbox wherever I need. I know how to do it programmatically/dynamically but without designer support. Perhaps I'm just missing something.

  • Is there a way how to make those menus design-able?
  • What is the best practice?

1条回答
姐就是有狂的资本
2楼-- · 2019-07-07 01:38

You can create a reusable custom context menu which is available in toolbox. To do so, it's enough to create a public class in the project which inherits from System.Windows.Forms.ContextMenuStrip and put the codes for creating items in constructor of your class.

Also you can do it using designer:

  • Add a new class CustomContextMenuStrip to your project
  • Make it public and inherit from System.Windows.Forms.ContextMenuStrip and save it.
  • Double click on file to open it in design mode which shows an empty area with a message which tells you can add some components.
  • In property window, click Items property and add items that you need.
  • It will creates the codes for items in InitializeComponent() method. Go to code view of the file and add a public parameterless constructor and call InitializeComponent() in it.
  • If you build the project, your custom component will add to toolbox in your project Components tab at top of toolbox.

Note:

  • Using the designer approach has benefits of using designer, for example using the designer, you can make your component localizable by setting Language property which is available only in designer. This way your component itself is localizable, independent from host form.
  • You can follow this approach for all components and controls which are inheritable and it's not restricted to ContextMenuStrip.
  • You can add behavior to menu items by adding event handlers in your custom class. Also if you need to let the forms that host your component add event handlers, you can hanlde ItemClicked in forms.
  • Whilst you can see those items in designer of host forms, but you can not change them using designer of the host forms.
查看更多
登录 后发表回答