从UserControl访问父表单控件

时间:2018-11-09 16:25:00

标签: c# winforms events button user-controls

我有一个安装向导,该向导将所有逻辑隐藏在一种窗体MainWindow中。

我想为安装的每个步骤创建专用的UserControl,并且我还想从MainWindow表单(如“下一页”和“后一页”按钮)访问某些控件。

因此,假设我要禁用/启用用户控件中的导航按钮。 我的解决方案是:

MainWindow表单:

public static void SetNavigationButtons(MainWindow mainwindow, bool SetBackPageButton, bool SetNextPageButton)
{
    mainwindow.NextPageButton.Enabled = NextPageBtn;
    mainwindow.BackPageButton.Enabled = BackPageBtn;
}

UserControl:

private void EnableNavButtons()
{
    MainWindow.SetNavigationButtons(ParentForm as MainWindow, true, true);
}

我还想到了EventHandlers:

UserControl:

public event EventHandler EnableNextPageButton;
public event EventHandler DisableNextPageButton;
public event EventHandler EnableBackPageButton;
public event EventHandler DisableBackPageButton;

private void EnableNavButtons()
{
    if (this.EnableNextPageButton != null)
       this.EnableNextPageButton(this, new EventArgs());

    if (this.EnableBackPageButton != null)
       this.EnableBackPageButton(this, new EventArgs());
}

并在MainWindow表单中捕获事件。

有人可以提供更好的解决方案吗?

1 个答案:

答案 0 :(得分:0)

在用户控件中,您可以像这样制作一个EventHandler。

    public event EventHandler yourevent;

    private void button1_Click(object sender, EventArgs e)
    {
        if (yourevent!= null) yourevent(this, new EventArgs());
    }

然后在表单加载事件中,您需要添加:

yourusercrontol.yourevent + = youreventname;

现在将其添加到表单中:

    public void youreventname(object sender, EventArgs e)
    {
          //your code for the form
    }