在winforms之间传递变量 [英] Passing variable between winforms

查看:19
本文介绍了在winforms之间传递变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have a problem concerning delegates in a Windows.Forms application.

有两种形式:

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

  1. the main form, which has a button named "Settings".

设置"表单,这是子"表单.

the "settings" form, this is the "child" form.

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

When I click the "Settings" button in the main form, it opens an instance of the Settings form.

我的问题是,当我打开它时,我需要将一个变量传递给设置表单.这样新表单将显示可变文本.我不知道如何检索子设置"表单中的信息.我通过在线学习教程来做到这一点,但从教程中无法理解如何阅读目标表单中的信息.

My problem is that I need to pass a variable to the Settings form, when I open it. So that the new form will show the variable text. I don't know how to retrieve the information in the child "Settings" form. I did this by following a tutorial online and could not understand from the tutorial how to read the info in the destination form.

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

Here's what I've done so far, the code in the main form:

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

推荐答案

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

Pass any information you want to in to the constructor of Settings form, and provide accessor methods for things you need out of there.

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

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

In the above "example" you can construct a SettingForm with a string and get at an integer it may use. In your code:

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
}

这篇关于在winforms之间传递变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆