1

如果我有这样的成员、构造函数和方法

//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()
{

}

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

4

1 回答 1

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!
        }
    }
}
于 2013-01-24T13:24:08.143 回答