c# - 调用 Form 1 中的方法从用户控件中设置文本
问题描述
我发现了与此类似的问题,但没有一个答案解决了我的问题 - 或者我可能不理解直接实施到我的场景的答案。
我已经开始学习 Windows 窗体,我的问题似乎很基础。
我有一个文本框myTextBox
,Form1
并在 Form1.cs 中创建了一个方法来设置文本。
public void SetText(string text)
{
myTextBox.Text = text;
}
我可以从 Form1.cs 中调用它,并且效果很好。
但是,我创建了一个用户控件,并且在该控件中我有一个按钮,当我单击该按钮时,我希望能够调用该SetText
方法,所以我这样做Form1.SetText("example")
了,但这给出了一个错误,解决了将“静态”添加到该SetText
方法的问题。
但是,当我添加静态时,SetText
我不能再在该方法中设置文本。我在添加静态之前遇到了同样的错误,只是这次是针对文本框本身:非静态字段、方法或属性“Form1.myTextBox”需要对象引用
解决方案
我不建议使用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")
.
推荐阅读
- arrays - 将变量分配给指针与将 & 变量分配给指针
- python - 如何在虚拟环境中使用不同的 python3.x 版本的 python
- mysql - 用户总是使用护照重定向失败?
- javascript - 使用ajax更新Mysql数据库表
- python - 当需要调用返回元组的函数时,简化列表理解
- java - OAuth 回调 URI 的 Android 深层链接不起作用
- python - 跟踪分类数据框列中的更改
- javascript - 如何在 React 中渲染特定数量的元素
- java - 属性 android:configChanges 和它的接受值
- python - 如何在我的问题中定义更多选项?