简体   繁体   中英

Can I trigger an event when a string changes from another class?

I have a string in my Main class and I have another class that I would like to trigger an event when the string from the main class changes. Many more classes could have events from the same string. How can I achieve that?

public class Mainclass
{
    private string _employe;
    public string Employe { get { return _employe; } set { _employe = value; } }
}

public class SecondClass
{
    public void StringChangedEvent()
    {
        //Stuff happen when Employe from MainClass changes
    }
}

public class ThirdClass
{
    public void StringChangedEvent()
    {
        //Stuff happen when Employe from MainClass changes
    }
}

You need to implement INotifyPropertyChanged interface and then call a method to emit that event when it happens, super manual unfortunately

    class MainClass : System.ComponentModel.INotifyPropertyChanged
    {
        private string _employee;

        public event PropertyChangedEventHandler PropertyChanged;

        public string Employee
        {
            get => _employee;
            set
            {
                _employee = value;
                PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(nameof(Employee)));
            }
        }
    }

    class SecondClass
    {
        public SecondClass(MainClass mainClass)
        {
            mainClass.PropertyChanged += StringChangedEvent;
        }

        private void StringChangedEvent(object sender, PropertyChangedEventArgs args)
        {                
            if(args.PropertyName == "Employee")
            {
                //Stuff happen if ...
            }
        }
    }

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