提高在C#中的WinForms自定义事件 [英] Raise custom events in C# WinForms

查看:97
本文介绍了提高在C#中的WinForms自定义事件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一些活动我对我自己的创造,想知道如何养育他们,当我想要的。

I have some Events I created on my own and was wondering on how to raise them when I want.

也许我的应用程序设计也搞砸了,可能需要一起来看看,如果你喜欢的。

Probably my application design is also messed up, might take a look at that if you like.

这是结构

ProgramContext
 - Form MainWindow
  + Control TextBox
  + Control Button
  + ...

在这种情况下, MainWindow.TextBox 认为,在运行时经常更新一些信息。所以,我莫名其妙地需要它来刷新自己时,我想(这样它可以从数据库中,在那里它的存储加载其数据)

In this case, the MainWindow.TextBox holds some information that is updated quite often at runtime. So, I somehow need it to refresh itself when I want to (so it can reload its data from the database, where the it's stored)

我试图钩住一个事件处理程序验证 - 活动,但似乎并没有这样的伎俩。

I tried hooking an EventHandler to its Validating-Event, but that didn't seem to do the trick.

所以,基本上我有重新加载数据 ProgramContext

So, basically I have a method that reloads the data in ProgramContext

DataTable table = _adapter.GetData();
foreach (DataRow row in table.Rows)
{
  MainWindow.TextBox.Text += table.Text.ToString();
}

这需要做每当另一种方法(即写入新数据进)被执行。

That needs to be done whenever another method (that writes new data into table) is executed.

任何想法?

推荐答案

编辑:看来你的问题更多的是挂钩到一个特定的事件,但低于FWIW是如何火一般的自定义事件

Edit : It seems your question is more about hooking into a specific event, but FWIW below is how to fire custom events in general.

处理更改事件文本框

据我了解,你想外方监控从一个文本框在窗体上引发的事件,然后为另一种形式的重新加载数据?

From what I understand, you want an external party to monitor events raised from a textbox on a Form and then to reload data on another form?

一个快速和肮脏的将是使表单文本框公众,然后其他人可以订阅该事件

A quick and dirty would be to make the Form TextBox public and then others could subscribe to this event

MainForm.textBox1.TextChanged += new System.EventHandler(this.textBox1_TextChanged);

或在较新版本的C#:

MainForm.textBox1.TextChanged += this.textBox1_TextChanged;



添加自定义的事件

另外,更清洁的方法是的提出一个自定义事件, - 如 MyDataChangedEvent 下面。这将允许你抽象掉的事实,更改从一个文本框都来了。

Another, cleaner way would be to raise a custom event, - e.g. MyDataChangedEvent below. This will allow you to abstract away the fact that the changes are coming from a textbox at all.

// Assuming you need a custom signature for your event. If not, use an existing standard event delegate
public delegate void myDataChangedDelegate(object sender, YourCustomArgsHere args);

// Expose the event off your component
public event myDataChangedDelegate MyDataChangedEvent;

// And to raise it
var eventSubscribers = MyDataChangedEvent;
if (eventSubscribers != null)
{
   eventSubscribers(this, myCustomArgsHere);
}



您可能还看耳鼻喉科库复合应用程序块和智能客户端软件工厂 - 这对整个UI同步SmartParts(控制,形成对话等)在一个松散耦合的方式非常灵活的事件经纪/酒馆子机制(CAB现在很过时)

这篇关于提高在C#中的WinForms自定义事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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