C#:需要我的一个类触发另一个类中的事件来更新文本框 [英] C#: Need one of my classes to trigger an event in another class to update a text box

查看:1257
本文介绍了C#:需要我的一个类触发另一个类中的事件来更新文本框的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

总的n00b到C#和事件,虽然我一直在编程了一段时间。

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...

任何想法?!

推荐答案

您的代码应该看起来像

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#:需要我的一个类触发另一个类中的事件来更新文本框的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆