1

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.

4
  • is it a WPF application? Commented Dec 2, 2014 at 18:24
  • No, it is a WinForm (C#) application. Commented Dec 2, 2014 at 18:28
  • Do you mind using the ReactiveUI framework? While I haven't used it for WinForms it has support for it. stackoverflow.com/questions/24768640/… Commented Dec 2, 2014 at 18:34
  • You need to learn about C# events. Commented Dec 2, 2014 at 18:43

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks. I had a feeling I was getting PropertyChanged from the INotifyPropertyChanged. When is the Observer created?
As soon as a UIElement in XAML has a Binding on this Object e.g. the Text Property of a TextBox

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.