开发者

Adding an event handerler to a custom control

开发者 https://www.devze.com 2023-03-27 03:15 出处:网络
I have a custom control i have created with a picture box, a label, and a combobox, i want to create a custom SelectedIndexChanged event handerler so i can perform actions when the index has been chan

I have a custom control i have created with a picture box, a label, and a combobox, i want to create a custom SelectedIndexChanged event handerler so i can perform actions when the index has been changed of the combobox, but with it being a custom control this event is not available to me by default,开发者_运维问答 so im hoping i can create one. custom controls and events are new to me. any help would be apreciated, thanks a lot.


if you just want to fire the event without telling which items are now selected you can do this with:

public event EventHandler SelectionChanged;

protected virtual void OnSelectionChanged() {
    if (SelectionChanged != null) {
        SelectionChanged(this, new EventArgs());
    }
}

just call OnSelectionChanged() within your control and the event SelectionChanged will be fired.

If you also want to tell which elements are now selected you can use the following, just replace object[] with your objectarray:

public event SelectionChangedEventHandler SelectionChanged;
public delegate void SelectionChangedEventHandler(object sender, SelectionChangedEventArgs e);

protected virtual void OnSelectionChanged(object[] SelectedItems) {
    if (SelectionChanged != null) {
        SelectionChanged(this, new SelectionChangedEventArgs(SelectedItems));
    }
}

public class SelectionChangedEventArgs : EventArgs {
    public object[] SelectedItems { get; private set; }

    public SelectionChangedEventArgs(object[] SelectedItems) {
        this.SelectedItems = SelectedItems;
    }
}
0

精彩评论

暂无评论...
验证码 换一张
取 消