NotifyPropertyChanged through code

走远了吗. 提交于 2019-12-11 16:33:40

问题


I have a class that contains two other objects.

A variable in the first object bind to WPF element, call it X.

A similar variable in the other object.

I want that when the PropertyChanged event happens, it will change the variable in the second object.

Here is the code that does not work for me:

The class that contains the variables: (I had register to property changed event)

private Class1 _var1;
    public Class1 Var1
    {
        get { return _var1; }
        set
        {
            _var1= value;
            if (_var1!= null)
                _var1.PropertyChanged += new PropertyChangedEventHandler(_var1_PropertyChanged);
            else
                _var1.PropertyChanged -= new PropertyChangedEventHandler(_var1_PropertyChanged);
        }
    }

    void _var1_PropertyChanged(object sender, PropertyChangedEventArgs e)
    {
      if(e.PropertyName=="X")
        Var2.X= Var1.X;
    }

    private Class2 _var2;
    public Class2 Var2
    {
        get { return _var2; }
        set { _var2= value; }
    }

Class 1:

    private int _x;
    public int X
    {
        get { return _x; }
        set
        {
            if (_x!= value)
            {
                _x= value;
                NotifyPropertyChanged("X");
            }
        }
    }

class 2:

public int X { get; set; }

PropertyChanged work in class 1 but he did not come to an event I created in a class that contains the two variables, why?


回答1:


I'm not sure I understand exactly what you mean, but if I had a class with 2 variables that I wanted to change together, I would try the following:
First, define some SetAndNotify method or you'll get a headache from the PropertyChanged events:

public void SetAndNotify<T>(ref T field, T value, Expression<Func<T>> exp)
{
    if (!Equals(field, value))
    {
        field = value;
        OnPropertyChanged(exp);
    }
}

Add it to some base class that will handle this event.

Second, in your setter for Var1 you register for the change event and not set anything, is that on purpose?

Third and last, there's no problem with changing more than one property in a setter, but make sure it's the public property that you change:

private SomeType privateVar1;
public SomeType PublicVar1
{
    get { return privateVar1; }
    set
    {
        SetAndNotify(ref privateVar1, value, () => PublicVar1);
        MyOtherPublicVar = someNewValue; // this will activate the property's setter.       
    }
}

I hope this helps. If not, please try to clarify your question.



来源:https://stackoverflow.com/questions/15240387/notifypropertychanged-through-code

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