Data binding without INotifyPropertyChanged
Update Controls does not require that you implement INotifyPropertyChanged or declare a DependencyProperty. It connects controls directly to CLR properties. It discovers dependencies upon data through layers of intermediate code. This makes it perfect for the Model/View/ViewModel pattern; no extra code is needed in the ViewModel, which sits between the Model and the View.
Wrap the DataContext of your Window. The wrapper not only implements INotifyPropertyChanged for all of your object's properties, it also automatically detects their dependencies on other properties. There is no base class or interface to implement.
public partial class Window1 : Window { public Window1() { InitializeComponent(); DataContext = ForView.Wrap(new PersonPresentation(new Person())); } }
public class PersonPresentation { private Person _person; public PersonPresentation(Person person) { _person = person; } public Person Person { get { return _person; } } public string FirstLast { get { return _person.FirstName + " " + _person.LastName; } } public string LastFirst { get { return _person.LastName + ", " + _person.FirstName; } } public string Title { get { return "Person - " + (_person.DisplayStrategy == 0 ? FirstLast : LastFirst); } } }
When you add a field to a data object, select the field and press Ctrl+D, G. The Update Controls Visual Studio add-in creates a property to wrap the field. It adds the code required to keep track of changes to the data field.
public class Person { private string _firstName; private string _lastName; private int _displayStrategy; #region Independent properties // Generated by Update Controls -------------------------------- private Independent _indDisplayStrategy = new Independent(); private Independent _indFirstName = new Independent(); private Independent _indLastName = new Independent(); public string FirstName { get { _indFirstName.OnGet(); return _firstName; } set { _indFirstName.OnSet(); _firstName = value; } } public string LastName { get { _indLastName.OnGet(); return _lastName; } set { _indLastName.OnSet(); _lastName = value; } } public int DisplayStrategy { get { _indDisplayStrategy.OnGet(); return _displayStrategy; } set { _indDisplayStrategy.OnSet(); _displayStrategy = value; } } // End generated code -------------------------------- #endregion }
The rest is taken care of. As the user changes the independent properties in the underlying data object, Update Controls refreshes the dependent properties in the presentation object.