简体   繁体   English

自定义控件WinForm的C#自定义事件

[英]C# Custom event for Custom Control WinForm

I have searched for this ,and there are several answers but I couldn't figure out how to do it. 我已经搜索过了,有几个答案,但是我不知道该怎么做。

I have a custom control with textbox and listview. 我有一个带有文本框和列表视图的自定义控件。 When a user starts typing on the textbox the listview is filled with all possible matches to the text typed.(it is a search box for users). 当用户开始在文本框中键入内容时,列表视图将填充所有与键入的文本匹配的内容。(这是用户的搜索框)。 User is typing customer names to find the customer. 用户正在输入客户名称以查找客户。

What I want to do is , when the user types in a customer and the customer is selected , I need to pass the customer name from custom control's textbox to my main project. 我想要做的是,当用户输入客户并选择了客户时,我需要将客户名称从自定义控件的文本框中传递到我的主项目中。

To do this , I think, I need a custom event, when a customer is selected , it raises an event to let the main application know. 为此,我认为我需要一个自定义事件,当选择一个客户时,它将引发一个事件以通知主应用程序。

How can I do this , thanks in advance. 我该怎么做,谢谢。

You need to do three things. 您需要做三件事。

1.Define the event in your custom control (for now, no special event arguments are added). 1.在自定义控件中定义事件(目前,未添加任何特殊事件参数)。

public event EventHandler CustomerSelected { get; set; }
private void OnCustomerSelected() {
    var customerSelected = CustomerSelected;
    if (customerSelected != null) {
        customerSelected(this, EventArgs.Empty);
    }
}

2.Fire the event when necessary. 2.必要时触发事件。 You can do this in your custom control by calling the OnCustomerSelected-method when a customer is selected. 您可以通过在选择客户时调用OnCustomerSelected方法在自定义控件中执行此操作。

3.Handle the event in your main form. 3.以您的主要形式处理事件。 You can do this by something like this (I've used a lambda, you can also define an eventhandler method, whatever you like). 您可以使用类似的方法来做到这一点(我使用过lambda,也可以定义一个事件处理程序方法,无论您喜欢什么)。

this.customerControl1.CustomerSelected += (s,e) => {
    // This runs when a customer is selected.
};

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM