C#:需要我的一个类来触发另一个类中的事件来更新文本框

总共n00b到C#和事件虽然我已经编程了一段时间。

我有一个包含文本框的类。 此类创建从串行端口接收帧的通信管理器类的实例。 我这一切都很好。

每次接收到一个帧并提取其数据时,我想要一个方法在我的类中使用文本框运行,以便将此帧数据附加到文本框。

所以,没有发布我的所有代码,我有我的表单类…

public partial class Form1 : Form { CommManager comm; public Form1() { InitializeComponent(); comm = new CommManager(); } private void updateTextBox() { //get new values and update textbox } . . . 

我有我的CommManager课程

 class CommManager { //here we manage the comms, recieve the data and parse the frame } 

所以……基本上,当我解析那个框架时,我需要从表单类中运行updateTextBox方法。 我猜这是可能的事件,但我似乎无法让它工作。

我在创建CommManager实例后尝试在表单类中添加一个事件处理程序,如下所示…

  comm = new CommManager(); comm.framePopulated += new EventHandler(updateTextBox); 

…但我必须做错了,因为编译器不喜欢它……

有任何想法吗?!

您的代码应该类似于:

 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事件命名指南的链接:

MSDN – 事件命名指南

在这里你有“最简单的C#事件示例可想象”。

 public partial class Form1: Form { CommManager comm; public Form1() { InitializeComponent(); comm = new CommManager(); comm.OnFramePopulated += new EventHandler(updateTextBox); } private void updateTextBox(object sender, EventArgs ea) { //update Textbox } } class CommManager { public EventHandler OnFramePopulated; public void PopulateFrame() { OnFramePopulated(this, null); } } 

是 – 将updateTextBox的签名更改为:

 private void updateTextBox(object sender, Eventargs ea) 

虽然这可能不是最好的设计。 如果你写了一个合适的事件处理程序,然后从那里调用updateTextBox,事情看起来会更整洁……