Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Binding between properties of two objects that both implements INotifyPropertyChanged in code

Tags:

.net

binding

wpf

I am trying to bind two properties from two different object that both implements INotifyPropertyChanged in code:

    public class ClassA : INotifyPropertyChanged
    {
        // leaving out the INotifyPropertyChanged Members for brevity

        public string Status
        {
            get { return _Status; }
            set { _Status = value; RaiseChanged("Status"); }
        }

    }

    public class ClassB : INotifyPropertyChanged
    {
        // leaving out the INotifyPropertyChanged Members for brevity

        public string Status
        {
            get { return _Status; }
            set { _Status = value; RaiseChanged("Status"); }
        }

    }

Is there a way I can bind these two properties in code together something like I would do if one of them was a 'proper' dependency property? Something like this?

ClassA classA = new ClassA();
ClassB classB = new ClassB();

Binding bind = new Binding("Status");
bind.Source = classA;
classB.SetBinding(ClassB.StatusProperty, bind);

Thanks!

like image 771
Marcel Avatar asked Nov 05 '22 02:11

Marcel


1 Answers

Late response, but...KISS:

ClassA classA = new ClassA();
ClassB classB = new ClassB();

classA.PropertyChanged += (s, e) => {
    if (e.PropertyName == "Status")
        classB.Status = classA.Status;
};

Voila, "binding" between INPC objects :) You can easily create a very simple helper class that does this for you with a single method call if you plan to do this often.

like image 93
Mike Marynowski Avatar answered Nov 11 '22 20:11

Mike Marynowski