user2970916
user2970916

Reputation: 1186

Two Way Data Binding without XAML

I have a class that I want to use to update a textbox when one of its properties changes. I also want to be able to change the classes property when the textbox changes. In other words, I want to be able to have two-way databinding. I have looked online, and all the example require a XAML file. As I am not familiar with XAML, I would like to stay away from that if it is possible.

Is it possible to have a two-way databinding with a class without using XAML?

Update:

I found this http://msdn.microsoft.com/en-us/library/ms743695%28v=vs.110%29.aspx, and it seems to work. However, I do not entirely understand what it is doing.

More specifically, I do not understand how PropertyChanged and OnPropertyChanged relate to each other.

Upvotes: 1

Views: 532

Answers (1)

Andreas Weswaldi
Andreas Weswaldi

Reputation: 131

In C# WPF you get PropertyChanged when you implement INotifyPropertyChanged.

So, if you write

PropertyChanged(this,  new PropertyChangedEventArgs("PersonName"));

You give the Observer (XAML) the Signal that the Property PersonName changed and it will update all e.g. UIElements linked to that Property.

With

 protected void OnPropertyChanged(string name)
  {
      PropertyChangedEventHandler handler = PropertyChanged;
      if (handler != null)
      {
          handler(this, new PropertyChangedEventArgs(name));
      }
  }

you overload the name of the Property (e.g. PersonName) as a string to signal which Property has changed.

With the if(handler != null) you say that you only send the signal if there is any Observer.

If so, in the next line you really give the Signal.

Upvotes: 2

Related Questions