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

查看:200
本文介绍了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
}

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

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