当注入对象的属性发生更改时,在类中调用方法

时间:2013-01-24 13:07:32

标签: c# dependency-injection

如果我有一个成员,构造函数和方法,那么

//The injected object exposes a public property of type bool which will raise
//a NotifyPropertyChangedEvent
IInjectedObject _injectedObject;

public someClass(IInjectedObject injectedObject)
{
    _injectedObject = injectedObject;
}

public void DoSomething()
{

}

当注入对象的属性发生变化时,有没有办法在我的类中调用该方法?

1 个答案:

答案 0 :(得分:2)

您声明您的接口继承自INotifyPropertyChanged,因此可以合理地期望通过“PropertyChanged”事件通知侦听器属性更改。假设这样的事情:

public interface IInjectedObject : INotifyPropertyChanged
{
    bool MyImportantProperty { get; }
}

然后,您的从属对象必须侦听INotifyPropertyChanged.PropertyChanged事件:

public class MyDependantClass
{
    public MyDependantClass(IInjectedObject injectedObject)
    {
        MyInjectedObject = injectedObject;
    }

    // We wrap the private field in a protected property,
    // to capture the event subscriptions
    private IInjectedObject _myInjectedObject;
    protected IInjectedObject MyInjectedObject
    {
        get { return _myInjectedObject; }
        set
        {
            // unsubscribe from the old property's event
            if(_myInjectedObject!= null)
                _myInjectedObject.PropertyChanged -= OnPropertyChanged;

            _myInjectedObject= value;

            // subscribe to the new property's event
            if(_myInjectedObject!= null)
               _myInjectedObject.PropertyChanged += OnPropertyChanged;
        }
    }

    private void OnPropertyChanged(object sender, PropertyChangedEventArgs args)
    {
        if(args.PropertyName == "MyImportantProperty")
        {
            //react to the changed property here!
        }
    }
}