问题
In C# (and Visual Basic) you can add several non-UI components (those that don't inherit from System.Windows.Forms.Control
) directly from the form designer. Examples of those components are System.Windows.Forms.FolderBrowserDialog
and System.Windows.Forms.Timer
.
But what's the benefit from adding non-UI controls with the UI designer instead of instancing them directly from code? There's a rationale behind that?
回答1:
I think using non-UI components in designer at least has these benefits:
Design-Time Support
One of most powerful things that you have in windows forms is the ability to use designer to setup Components.
Even though Timer
is not a UI component, but you can set its properties like interval at design time. This applies to many other components like BindingSource
, ErrorProvider
, ... that you can use very friendly property grid and type editors and type converters to configure properties at design time.
- When you want to configure dependent properties for other controls; for example by adding
BindingSource
to designer, it makes data binding very easy. - When you need to use extender providers like
HelpProvider
andTooltip
, since they are related to other controls, it is very easy to configure them at design mode. - When you need to configure properties like
DataSource
andDataMember
, it is very friendly to use designer and use great property grid features. - Components will add as class level fields, and you can make them public using deigner.
- When you need to use
Localizable
feature ofForm
for your components, it's completely available using designer. - When you need to simply add or remove event handlers you can do it using property grid.
Standard Code
If you take a look at designer generated code you will see:
- Generated code for components that supports
ISupportInitialize
uses theirBeginInit
andEndInit
- Generated code for components, pass
this.components
to constructor and then use it whenDispose
If you don't need design-time support and you write standard code for components, so it's completely OK to use theme in code.
来源:https://stackoverflow.com/questions/32800751/why-should-i-insert-a-non-ui-windows-forms-component-from-the-designer