Good practice to show Form from UserControl

220 views Asked by At

I want to follow good practices design patterns when developing WinForms applications.

I have a UserControl with a button "Add" to open a new Form where de user can search Employees. How i can organize my code?

1

There are 1 answers

0
Mateusz Radny On

If you use WinForms you should use MVP (Model-View-Presenter) design pattern. In this case each view has own ISomethingView which contains the properties and the events, for example:

    public interface IBaseView
    {
       void Show();
       void Close();
    }

    public interface ILoginView : IBaseView
    {
       string Login { get; }
       string Password {get; }
       event EventHandler SignIn { get; }
    }

And now your UserControl must implemented this interface.

Also for each view you have to create a presenter which is responsible for communication between the view and a business logic:

    public LoginPresenter
    {
       // private variables 

       public LoginPresenter(ILoginView loginView, IOtherView otherView)
       {
           this.loginView = loginView;
           this.otherView = otherView;

           this.loginView.SignUp += OnSignUp;
       }

       private void OnSignUp(object sender, EventArgs eventArgs)
       {
            if (this.authService.Login(this.loginView.UserName, this.loginView.Password))
            {
                this.loginView.Close();
                this.otherView.Show();
            }
       }
    }

You can use DI container to resolve all I*Vies, for example:

    public class LoginUserControl : UserControl, ILoginView
    {
        public LoginUserControl()
        {
             this.loginPresenter = new LoginPresenter(this, DIContainer.Resolve<IOtherView>());
        }
    }