Bind one property to another and chain/fire OnPropertyChanged

萝らか妹 提交于 2019-12-11 11:14:27

问题


I'm binding to properties from XAML in a WPF application, but this query is about raising 'PropertyChanged' events on one class property when another is raised in a different class/object. One use case is where a combobox ItemsSource binds to a property (PropB in my simplified example below) and that property returns a collection based on other properties (PropA below). PropB in class B needs to raise PropertyChanged when PropA in class A changes, but class A does not reference class B.

Is there an existing method or framework to have a property of an INotifyPropertyChanged object raise 'OnPropertyChanged' when a property in another object changes?

Below is an example of what I'd like to do using a made-up "Notify" property attribute as a binding path:

public class A : NotifyPropertyChanged
{
    string m_PropA;
    public string PropA
    {
        get { return m_PropA; }
        set
        {
            if (m_PropA != value)
            {
                m_PropA = value;
                OnPropertyChanged("PropA");
            }
        }
    }
}

public class B : NotifyPropertyChanged
{
    public A ARef { get; private set; }

    string m_PropB;
    [Notify("ARef.PropA")]
    public string PropB
    {
        get { return ARef.PropA; }
    }
}

Ideally the attribute would create a binding to each property in the property path (ARef and PropA) and when either of them changed it would call OnPropertyChanged on class B passing in "PropB" as the propertyName argument. I'm assuming that the ARef property also needs to raise an event when changed, but it'd be nice if it didn't.

I'm guessing this would require a bit of reflection and weak event listeners. Hopefully something exists that I can use. Apologies if this has been answered before.


回答1:


Tip1 (Binding)

  • change your binding from Path=PropB to Path=ARef.PropA and add OnPropertyChanged into ARef setter in class B.
  • in this case value will be changed when you change ARef property in class B or PropA in class A

Tip2 (Event Chain)

  • In setter of A (in B) add event handler to PropertyChanged event of class A. n handler, Raise PropertyChangedEvent of PropB when arg contains PropA.
  • Manual Event Fire is a good way to forget something, and turn your application chaotic


来源:https://stackoverflow.com/questions/30012674/bind-one-property-to-another-and-chain-fire-onpropertychanged

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!