在winforms之间传递变量

Amc*_*tty 5 .net c# delegates winforms

我有一个关于Windows.Forms应用程序中的委托的问题.

有两种形式:

  1. 主窗体,有一个名为"设置"的按钮.

  2. "设置"表单,这是"子"形式.

当我单击主窗体中的"设置"按钮时,它会打开"设置"窗体的实例.

我的问题是,当我打开它时,我需要将一个变量传递给Settings表单.这样新表单将显示变量文本.我不知道如何检索子项"设置"表单中的信息.我是通过在线教程完成此操作,无法从教程中了解如何阅读目标表单中的信息.

这是我到目前为止所做的,主要形式的代码:

public partial class MainForm : Form
{

    /// <summary>
    /// delegate to send data between forms
    /// </summary>
    public delegate void PageInfoHandler(object sender, PageInfoEventArgs e);
    /// <summary>
    /// event of the delegate
    /// </summary>
    public event PageInfoHandler PageInfoRetrieved;

    //other stuff, events blabla

    private void toolStripBtnSettings_Click(object sender, EventArgs e)
    {
        PageInfoEventArgs args = new PageInfoEventArgs(SomeString);
        this.OnPageInfoRetrieved(args);

        SettingsForm settingsForm = new SettingsForm();
        settingsForm.ShowDialog();  
    }

    private void OnPageInfoRetrieved(PageInfoEventArgs args)
    {
        if (PageInfoRetrieved != null)
            PageInfoRetrieved(this, args);
    }
}
Run Code Online (Sandbox Code Playgroud)

Moo*_*ice 12

将您想要的任何信息传递给"设置"表单的构造函数,并为您需要的内容提供访问器方法.

public class SettingsForm : WinForm
{
    private string m_Data;
    private int m_nExample = 0;

    // ctor
    public SettingsForm(string _data)
    {
        m_Data = data;  // you can now use this in SettingsForm
    } // eo ctor

    public int Example {get{return(m_nExample);} }
} // eo class SettingsForm
Run Code Online (Sandbox Code Playgroud)

在上面的"示例"中,您可以使用字符串构造一个SettingForm,并获取它可能使用的整数.在你的代码中:

private void toolStripBtnSettings_Click(object sender, EventArgs e)
{
    PageInfoEventArgs args = new PageInfoEventArgs(SomeString);
    this.OnPageInfoRetrieved(args);

    SettingsForm settingsForm = new SettingsForm("some data to pass");
    settingsForm.ShowDialog();  

    int result = settingsForm.Example; // retrieve integer that SettingsForm used
}
Run Code Online (Sandbox Code Playgroud)


Kat*_*ory 5

Setttings表单是一个类.它现在是你的,你可以用它做你喜欢的事.因此,在其构造函数中添加一个参数(或许多你想要的参数).然后在你的MainForm中调用SettingsForm(无论如何),你就完成了.