I recently made a very simple app in WPF that simply reads data from a few TextBoxes and updates records in an SQL Server database. I also put back and forward buttons to allow the user to scroll through the available records. Everytime the user clicks Next on the app, the UI gets updated with the values from the new record through a method I called updateControls(), which looks like this:
private void updateControls()
{
IQueryable<Comment> query = from t in container.Comment
where t.Id == browseIndex
select t;
if (query.Count<Comment>() > 0)
{
currentComment = query.First<Comment>();
txtID.Text = currentThought.Id.ToString();
txtComment.Text = currentComment.thought;
txtDate.DisplayDate = currentComment.date;
txtDate.Text = currentComment.date.ToString();
}
}
This is simple, and it works like a charm. But I recently discovered the world of data-binding, where you can supposedly eliminate all this boilerplate code of manually updating controls and have them update themselves whenever the model changes.
After much experimentation and reading through various tutorials, I find that, for this to work, my data object must implement the INotifyPropertyChanged interface, which means need to use explicit setters on the properties I wish to update on my UI, like this:
public class Comment: INotifyPropertyChanged {
private string comment;
public event PropertyChangedEventHandler PropertyChanged;
public string Comment { get { return this.comment;}
set {
this.comment = value;
NotifyPropertyChanged("Comment");
}
public void NotifyPropertyChanged(string propName)
{
if (this.PropertyChanged != null ) this.PropertyChanged(this, new PropertyChangedEventArgs(propName));
}
}
This is a lot more code than simply manually updating my UI with the data I want. Also, since this class is part of an Entity Model, the INotifyPropertyChanged interface has to be implemented in a class apart from the model classes, since model classes get regenerated when the model is updated. Which leads me to my question: why ever would I want to use data-binding in a real world application when it is much simpler to simply update my UI manually? Or is there an alternative way to do this that I'm not seeing?
The MVVM pattern dissociates the GUI logic from the core logic.
There are many reasons why this pattern is great, there are plenty of articles on internet