[英]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您需要实现 INotifyPropertyChanged 接口,然后调用一个方法在发生该事件时发出该事件,不幸的是超级手动
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 ...
}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.