【问题标题】:Good practice to show Form from UserControl从 UserControl 显示表单的好习惯
【发布时间】:2017-05-09 08:23:55
【问题描述】:

我想在开发 WinForms 应用程序时遵循良好的实践设计模式。

我有一个带有“添加”按钮的用户控件,用于打开一个新表单,用户可以在其中搜索员工。如何组织我的代码?

【问题讨论】:

  • 您在使用带有 WinForms 的 MVVM 架构吗?您是否有明确定义的域/业务实体对象?我们需要有关您的应用程序的范围和设计的更多信息。
  • 我注意到,如果您想遵循绝对的最佳实践,您可能不会使用 WinForms。例如,使用 WinForms 而不是 WPF 的商业理由是什么?
  • 目前项目很简单,Employee类是EF创建的模型类的一部分,我想遵循MVP模式
  • 我只使用 WinForms

标签: c# winforms design-principles


【解决方案1】:

如果您使用 WinForms,您应该使用 MVP(模型-视图-演示者)设计模式。在这种情况下,每个视图都有自己的ISomethingView,其中包含属性和事件,例如:

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

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

现在你的 UserControl 必须实现这个接口。

您还必须为每个视图创建一个演示者,负责视图和业务逻辑之间的通信:

    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();
            }
       }
    }

您可以使用DI容器来解析所有I*Vies,例如:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-11-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多