首页 > 解决方案 > 调用 Form 1 中的方法从用户控件中设置文本

问题描述

我发现了与此类似的问题,但没有一个答案解决了我的问题 - 或者我可能不理解直接实施到我的场景的答案。

我已经开始学习 Windows 窗体,我的问题似乎很基础。

我有一个文本框myTextBoxForm1并在 Form1.cs 中创建了一个方法来设置文本。

public void SetText(string text)
{
   myTextBox.Text = text;
}

我可以从 Form1.cs 中调用它,并且效果很好。

但是,我创建了一个用户控件,并且在该控件中我有一个按钮,当我单击该按钮时,我希望能够调用该SetText方法,所以我这样做Form1.SetText("example")了,但这给出了一个错误,解决了将“静态”添加到该SetText方法的问题。

但是,当我添加静态时,SetText我不能再在该方法中设置文本。我在添加静态之前遇到了同样的错误,只是这次是针对文本框本身:非静态字段、方法或属性“Form1.myTextBox”需要对象引用

标签: c#winforms

解决方案


我不建议使用SetText,因为它与其他程序不兼容。

建议的解决方案:

  • TextBox财产:

添加您的用户控件TextBox属性,然后使用它。

代码示例: 在 UserControl.cs

public TextBox TargetTextBox { get; set; }

public void SetText(string text)
{
    TargetTextBox.Text = text;
}

并使用 UserControl 中可用的新方法

  • 事件:

在用户控件中添加事件,如果此事件在 中触发,则在此处的代码中Form1使用SetText

示例代码: 创建名为的文件TextEventArgs并放置以下代码:

public class TextEventArgs : EventArgs
{
    public TextEventArgs(string text)
    {
        Text = text;
    }
    public string Text { get; set; }
}

在用户控件中使用此代码

public delegate void ShowTextEventHandler(object sender, TextEventArgs e);
public event ShowTextEventHandler ShowText;

// Use this method, and this method will fire 'ShowText' event
protected override OnShowText(TextEventArgs args)
{
    TextEventHandler handler = ShowText;
    handler?.Invoke(this, args);
}
  • 变量(不建议):

进入Program.cs文件并将其替换为以下代码:

using System.Windows.Forms;

public class Program
{
    internal static readonly MainForm;

    static void Main()
    {
        Application.EnableVisualStyles();
        Application.SetCompitableTextRenderer(false);
        MainForm = new Form1();
        Application.Run(MainForm);
    }
}

然后你可以使用Program.MainForm.SetText("example").


推荐阅读