设置用户控件的默认事件 [英] Set User Control's default event
问题描述
我有一个 User Control
,其中包含一大堆控件。我想将这个 User Control
的默认事件设置为我的一个按钮的点击
事件。
I have a User Control
containing a bunch of controls. I want to set the default Event of this User Control
to the Click
event of one of my buttons.
我知道将默认事件设置为其中一个UserControl的事件我应该添加属性:
I know for setting default event to one of the UserControl's events I should add the attribute:
[DefaultEvent("Click")]
public partial class ucPersonSearch : UserControl
...
我想知道是否可以执行以下操作:
I'm wondering if it's possible to do something like:
[DefaultEvent("btn1_Click")]
public partial class ucPersonSearch : UserControl
...
我想在btn1被绑定的时候托管此用户控件的形式发起一些方法。
I want to fire some methods in the form hosting this User Control at the time btn1 is clikced.
这是我项目中的一个编织,你回答将有价值。
This is really a knit in my project, and you're answer will be valueable.
推荐答案
您不能将课程成员的事件公开到课外。其他人如何在 UserControl $ c中订阅
点击
事件 Button
$ C>?你试了吗?这是不可能的,除非你让外部的按钮可以访问,这是不好的(每个人都可以更改所有的属性)。
You can't expose events of your class members to the outside of the class. How can others subscribe to the Click
event of a Button
inside your UserControl
? Did you try it? It's not possible unless you make the button accessible from the outside, which is not good (everybody can change all the properties).
你必须定义一个新的事件,当您想要的活动(点击按钮)发生时,触发您的新活动:
You have to define a new event, and fire your new event when your desired event (clicking on the button) happens:
[DefaultEvent("MyClick")]
public partial class UCPersonSearch : UserControl
{
Button btnSearch;
public event EventHandler MyClick;
public UCPersonSearch()
{
btnSearch = new Button();
//...
btnSearch.Click += new EventHandler(btnSearch_Click);
}
void btnSearch_Click(object sender, EventArgs e)
{
OnMyClick();
}
protected virtual void OnMyClick()
{
var h = MyClick;
if (h != null)
h(this, EventArgs.Empty);
}
}
这篇关于设置用户控件的默认事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!