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

Mat*_*att 5 c# events event-handling

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

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

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

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

public partial class Form1 : Form
{
    CommManager comm;

    public Form1()
    {
        InitializeComponent();
        comm = new CommManager();

    }

    private void updateTextBox()
    {
        //get new values and update textbox
    }
    .
    .
    .
Run Code Online (Sandbox Code Playgroud)

我有我的CommManager课程

class CommManager 
{
     //here we manage the comms, recieve the data and parse the frame
}
Run Code Online (Sandbox Code Playgroud)

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

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

 comm = new CommManager();
 comm.framePopulated += new EventHandler(updateTextBox);
Run Code Online (Sandbox Code Playgroud)

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

有任何想法吗?!

Jus*_*ner 10

您的代码应该类似于:

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();
    }
}
Run Code Online (Sandbox Code Playgroud)

这里是评论中提到的.NET事件命名指南的链接:

MSDN - 事件命名指南