0

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?

apaz
  • 51
  • 3
  • Are you using the MVVM architecture with WinForms? Do you have clearly defined domain/business entity objects? We need more information about the scope and design of your application. – Dai Dec 23 '16 at 16:18
  • 1
    I note that if you want to follow absolute best-practices you might not be using WinForms. What is the business justification for using WinForms instead of WPF, for example? – Dai Dec 23 '16 at 16:19
  • Currently the project is simple, the Employee class is part of the model classes created by EF and I want to follow the MVP pattern – apaz Dec 23 '16 at 16:22
  • I just work with WinForms – apaz Dec 23 '16 at 16:26

1 Answers1

1

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>());
        }
    }
Mateusz Radny
  • 301
  • 1
  • 6