我有一个包含一堆控件的用户控件
。我想将此 User Control
的默认事件设置为我的其中一个按钮的 Click
事件。
我知道要将默认事件设置为 UserControl 的事件之一,我应该添加属性:
[DefaultEvent("Click")]
public partial class ucPersonSearch : UserControl
...
我想知道是否可以这样做:
[DefaultEvent("btn1_Click")]
public partial class ucPersonSearch : UserControl
...
我想在单击 btn1 时触发托管此用户控件的表单中的一些方法。
这真的是我项目中的一个编织物,你的回答将很有值(value)。
最佳答案
您不能将类(class)成员的事件公开给类(class)外部。其他人如何订阅您的 UserControl
中的 Button
的 Click
事件?你试过了吗?这是不可能的,除非你让按钮可以从外部访问,这是不好的(每个人都可以更改所有属性)。
你必须定义一个新事件,并在你想要的事件(点击按钮)发生时触发你的新事件:
[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);
}
}
关于c# - 设置用户控件的默认事件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14956703/