在 c# 中的用户控件中公开和引发子控件的事件
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/943171/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
expose and raise event of a child control in a usercontrol in c#
提问by Anirudh Goel
Hi. I have a UserControl which contains a textbox. I wanted to access the textchanged event of the textbox but in the event properties of the usercontrol I don't see the events for the textbox. How can I expose and handle particular events of the child controls from the publicly exposed UserControl in Winforms with C#.
你好。我有一个包含文本框的 UserControl。我想访问文本框的 textchanged 事件,但在用户控件的事件属性中,我没有看到文本框的事件。如何使用 C# 在 Winforms 中公开和处理来自公开公开的 UserControl 的子控件的特定事件。
采纳答案by Matt Hamilton
You can surface a new event and pass any subscriptions straight through to the control, if you like:
如果您愿意,您可以显示一个新事件并将任何订阅直接传递给控件:
public class UserControl1 : UserControl
{
// private Button saveButton;
public event EventHandler SaveButtonClick
{
add { saveButton.Click += value; }
remove { saveButton.Click -= value; }
}
}
回答by Galilyou
Expose the entire TextBox as a public property in user control and subscribe to it's events the way you desire.
Example:
将整个 TextBox 公开为用户控件中的公共属性,并以您想要的方式订阅它的事件。
例子:
class myUserControl: UserControl {
private TextBox _myText;
public TextBox MyText { get {return _myText; } }
}
}
After doing this you can subscribe on any of its events like so:
完成此操作后,您可以订阅其任何事件,如下所示:
theUserControl.MyText.WhatEverEvent += ...
Hope this helps!
希望这可以帮助!