问题描述
我有一个USerControll中,我有一个文本框。我用的是用户控件在我的形式,我希望当有人压在文本框中输入要做点什么。我该怎么办呢?
如果你告诉我如何手动调用事件,我可以打电话textbox.keydown usercontrol.keydown。
I have a USerControll in which i have a textbox. I use the usercontrol in my form, I want to do something when somebody presses enter on the textbox. how can I do it?if you tell me how to call an event manually, I can call usercontrol.keydown in textbox.keydown.
推荐答案
首先,事件只能从代码声明该事件的控制范围内提高。所以,你的用户控件声明自定义事件KeyDown以提高它。你不能,例如,提高的KeyDown对用户控件包含一个文本框。不过,你可以声明自己的KeyDown和附加处理的文本框的的KeyDown,将提高自己的KeyDown
First, events can only be raised from code within the control that declares the event. So, your user control has to declare the custom event KeyDown in order to raise it. You cannot, for instance, raise KeyDown on a TextBox contained by your user control. However, you can declare your own KeyDown, and attach a handler to the TextBox's KeyDown that will raise your own KeyDown.
由于这种限制,引发一个事件很简单:
Given this restriction, raising an event is easy:
public delegate void MyEventHandler(object sender, MyEventArgs e)
public event MyEventHandler MyEvent;
public void RaisesMyEvent()
{
...
if(MyEvent != null) //required in C# to ensure a handler is attached
MyEvent(this, new MyEventArgs(/*any info you want handlers to have*/));
}
引发事件看起来很像一个方法,因为在本质上这就是你正在做;你调用分配给您的活动幕后的多播委托一个或者多个方法委托。把它看成是分配给一个普通的名为委托的方法(如果你省略喜欢自定义的事件关键字),并从你的代码中调用它。一个真实的事件和那之间的唯一区别是,一个事件可以有多个处理程序委托重视它,并提出当将调用所有的人。
Raising an event looks much like a method, because in essence that's what you're doing; you're calling one or more method delegates that are assigned to the MultiCast delegate behind the scenes of your event. Think of it as assigning a method to an ordinary named delegate (like if you'd omitted the "event" keyword from the definition) and calling it from inside your code. the only difference between a true event and that is that an event can have more than one handler delegate attached to it, and will invoke all of them when raised.
这篇关于如何在C#中手动调用的事件吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!