简体   繁体   English

C#在自定义控件中获取控件的事件

[英]C# Get Events of a Control inside a Custom Control

I have a listbox inside a custom control. 我在自定义控件中有一个列表框。 I use this custom control into a form. 我将此自定义控件用于表单。 I would like to be able to get the listbox index changed event when I am working into the form. 我希望能够在我处理表单时获取列表框索引更改事件。 How can I do that? 我怎样才能做到这一点?

If you are using WinForms, then you need to wire this event manually. 如果您使用的是WinForms,则需要手动连接此事件。 Create event with the same signature on your custom control, create a handler for the even on the original listbox inside your custom control and in this handler fire the newly created event. 在自定义控件上创建具有相同签名的事件,在自定义控件内的原始列表框上为偶数创建处理程序,并在此处理程序中触发新创建的事件。 (ignore all of this if you are using WPF) (如果您使用WPF,请忽略所有这些)

You can add a proxy event to the custom control 您可以将代理事件添加到自定义控件

public event EventHandler<WhatEverEventArgs> IndexChanged { 
    add { listBox.IndexChanged += value; }
    remove { listBox.IndexChanged -= value; } 
}

This can be a disadvantage of a UserControl. 这可能是UserControl的缺点。 You have to re-publish the events and the properties of one or more of its embedded controls. 您必须重新发布一个或多个嵌入式控件的事件和属性。 Consider the alternative: if this UserControl only contains a ListBox then you are much better off simply inheriting from ListBox instead of UserControl. 考虑另一种选择:如果此UserControl只包含一个ListBox,那么只需继承ListBox而不是UserControl就会好得多。

Anyhoo, you'll need to re-fire the SelectedIndexChanged event. Anyhoo,你需要重新激活SelectedIndexChanged事件。 And surely you'll need to be able to let the client code read the currently selected item. 当然,您需要能够让客户端代码读取当前选定的项目。 Thus: 从而:

public partial class UserControl1 : UserControl {
    public event EventHandler SelectedIndexChanged;

    public UserControl1() {
        InitializeComponent();
    }

    private void listBox1_SelectedIndexChanged(object sender, EventArgs e) {
        EventHandler handler = SelectedIndexChanged;
        if (handler != null) handler(this, e);
    }
    public object SelectedItem {
        get { return listBox1.SelectedItem; }
    }
}

Look into Ninjects Extension the MessageBroker, and on the index changed raise a published event, and subscribe to the event on the form side. 查看Ninjects Extension MessageBroker,并在索引更改时引发已发布的事件,并在表单端订阅该事件。

The messagebroker is rather useful in most cases. 在大多数情况下,消息经纪人非常有用。

Another thought would be implement an observer pattern and add the form as an observer to the controls event. 另一个想法是实现一个观察者模式,并将该表单作为观察者添加到controls事件中。

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

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