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
}
}
CodePudding user response:
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 ...
}
}
}