简体   繁体   中英

Does a window's default constructor have to be public?

I'm working on a dialog window for my WPF application. I know that WPF requires that all controls have a default constructor and I can create all the constructors that take all the parameters that I want. But does the default constructor have to be public? Can I make it internal, or private, or even protected?

Controls dont need a default constructor in WPF, unless you want to instantiate the control from XAML.

It's perfectly legal to have a control like this:

public partial class MyUserControl : UserControl
{
      public MyUserControl(string someParameter) : this()
      { 
         InitializeComponent();
      }
}

As shown, the default constructor was removed, you need to make sure that InitializeComponent(); is called, though.

If you instantiate the control from XAML, then the default constructor must be visible by the embedding control

Therefore it can be internal if the embedding control is in the same assembly, or it has to be public otherwise.

making your constructor internal ensures the type will only ever be instantiated by types within the current assembly, even if it is later decided that the type itself should be public instead of internal. In other words you could decide to change the type's visibility without lifting restrictions on its instantiation.

Making the constructor public has the opposite effect (obviously), and might be sensible if you want for it to be possible to instantiate the type anywhere it is visible.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM