C#: Need one of my classes to trigger an event in another class to update a text box(C#:需要我的一个类来触发另一个类中的事件以更新文本框)
问题描述
尽管我已经编程了一段时间,但 C# 和事件的总 n00b.
Total n00b to C# and events although I have been programming for a while.
我有一个包含文本框的类.此类创建从串行端口接收帧的通信管理器类的实例.我有这一切工作正常.
I have a class containing a text box. This class creates an instance of a communication manager class that is receiving frames from the Serial Port. I have this all working fine.
每次接收到帧并提取其数据时,我都希望在我的类中使用文本框运行一个方法,以便将此帧数据附加到文本框.
Every time a frame is received and its data extracted, I want a method to run in my class with the text box in order to append this frame data to the text box.
因此,无需发布我的所有代码,我就有了我的表单类...
So, without posting all of my code I have my form class...
public partial class Form1 : Form
{
CommManager comm;
public Form1()
{
InitializeComponent();
comm = new CommManager();
}
private void updateTextBox()
{
//get new values and update textbox
}
.
.
.
我有我的 CommManager 课程
and I have my CommManager class
class CommManager
{
//here we manage the comms, recieve the data and parse the frame
}
所以...本质上,当我解析该框架时,我需要运行表单类中的 updateTextBox 方法.我猜这在事件中是可能的,但我似乎无法让它发挥作用.
SO... essentially, when I parse that frame, I need the updateTextBox method from the form class to run. I'm guessing this is possible with events but I can't seem to get it to work.
在创建 CommManager 的实例后,我尝试在表单类中添加一个事件处理程序,如下所示...
I tried adding an event handler in the form class after creating the instance of CommManager as below...
comm = new CommManager();
comm.framePopulated += new EventHandler(updateTextBox);
...但是我一定做错了,因为编译器不喜欢它...
...but I must be doing this wrong as the compiler doesn't like it...
有什么想法吗?!
推荐答案
你的代码应该是这样的:
Your code should look something like:
public class CommManager()
{
delegate void FramePopulatedHandler(object sender, EventArgs e);
public event FramePopulatedHandler FramePopulated;
public void MethodThatPopulatesTheFrame()
{
FramePopulated();
}
// The rest of your code here.
}
public partial class Form1 : Form
{
CommManager comm;
public Form1()
{
InitializeComponent();
comm = new CommManager();
comm.FramePopulated += comm_FramePopulatedHander;
}
private void updateTextBox()
{
//get new values and update textbox
}
private void comm_FramePopulatedHandler(object sender, EventArgs e)
{
updateTextBox();
}
}
这里是评论中提到的 .NET 事件命名指南的链接:
And here's a link to the .NET Event Naming Guidelines mentioned in the comments:
MSDN - 事件命名指南
这篇关于C#:需要我的一个类来触发另一个类中的事件以更新文本框的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:C#:需要我的一个类来触发另一个类中的事件以更新文本框
基础教程推荐
- 如何使用 .Net 检查 Active Directory 服务器是否已启动并正在运行? 2022-01-01
- WPF 模态进度窗口 2022-01-01
- 我应该在后面的代码中直接使用 Linq To SQL 还是使 2022-01-01
- C# 从 List<List<int>> 中删除重 2022-01-01
- 如果有人提交恶意软件Nuget包怎么办? 2022-01-01
- Azure Functions:CosmosDBTrigger 未在 Visual Studio 中触发 2022-01-01
- 禁止输入少量字符,例如'<'、'&a 2022-01-01
- 当值可以是对象或空数组时反序列化 JSON 2022-01-01
- Moq It.Is<>不匹配 2022-01-01
- .NET SerialPort DataReceived 事件未触发 2022-01-01
