将一个属性绑定到另一个属性,并连锁/触发OnPropertyChanged

将一个属性绑定到另一个属性,并连锁/触发OnPropertyChanged

问题描述:

我绑定了WPF应用程序中XAML的属性,但是此查询涉及在另一个类/对象中引发另一个属性时,在一个类属性上引发'PropertyChanged'事件.一个用例是组合框ItemsSource绑定到属性(在下面的简化示例中为PropB),而该属性返回基于其他属性的集合(在下面的PropA).当A类中的PropA更改时,B类中的PropB需要提高PropertyChanged,但是A类没有引用B类.

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.

是否存在一个现有的方法或框架,当另一个对象的属性发生更改时,该对象具有INotifyPropertyChanged对象的属性会引发"OnPropertyChanged"?

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

下面是使用虚构的"Notify"属性属性作为绑定路径的示例示例:

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

理想情况下,该属性将创建对属性路径(ARef和PropA)中每个属性的绑定,并且当它们中的任何一个更改时,都将在类B上调用OnPropertyChanged,并将"PropB"作为propertyName参数传递.我假设ARef属性在更改时也需要引发一个事件,但是如果没有,那就很好了.

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(绑定)

  • 将您的绑定从Path = PropB更改为Path = ARef.PropA,并将OnPropertyChanged添加到B类的ARef设置器中.
  • 在这种情况下,当您在B类中更改ARef属性或在A类中更改PropA时,值将更改

提示2(事件链)

  • 在A的setter中(在B中)将事件处理程序添加到类A的PropertyChanged事件中.n处理程序,当arg包含PropA时引发PropB的PropertyChangedEvent.
  • 手动事件触发是一种忘记某些东西并使您的应用程序混乱的好方法