简体   繁体   中英

Custom Event in Custom Control (on variable changed)

I'm making a custom control including three buttons. Every button represents a tab. When I click a button to change to the tab corresponding to that tab a variable for the controll is uppdated, this variable is called "selectedIndex". How can I make a custom event that triggers when this index is changed?

I've seen solutions for custom events here but all of them is copies of already existing events such as Click-events. My problem involvs having an event on variable change".

Regards!

One option is to have your object implement the very standard INotifyPropertyChanged interface . There's no rule which states that every property on an object needs to raise the PropertyChanged event, so just raise it for the one property in question. Something like this:

public class MyObject : INotifyPropertyChanged
{
    private string _myProperty;
    public string MyProperty
    {
        get { return _myProperty; }
        set
        {
            _myProperty = value;
            NotifyPropertyChanged();
        }
    }

    public event PropertyChangedEventHandler PropertyChanged;

    private void NotifyPropertyChanged([CallerMemberName] string propertyName = "")
    {
        if (PropertyChanged != null)
            PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
    }
}

If your .NET version doesn't support CallerMemberName then you can remove that and supply the property name manually:

NotifyPropertyChanged("MyProperty");

At this point any calling code can subscribe to the public PropertyChanged event on any instance of this object. This interface is particularly handy because it's commonly used in lots of UI technologies for updating data-bound UI elements. All the interface enforces, really, is a standard name for the event. If you'd prefer, you can forgo the interface and just create a custom public event. And just invoke that event any time your object logically needs to. The structure of exposing an event and invoking it would be the same.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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