繁体   English   中英

当字符串从另一个类更改时,我可以触发事件吗?

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

我的主类中有一个字符串,我有另一个类,当主类中的字符串更改时,我想触发一个事件。 更多的类可以有来自同一个字符串的事件。 我怎样才能做到这一点?

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
    }
}

您需要实现 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.

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