Whether you writing a Windows Forms or WPF application there’s a good chance you'll want to leverage the support both platforms have for data binding by constructing a data model that can be observed by the views in you application. One way to achieve this in .NET is by implementing the INotifyPropertyChanged interface, which is supported by the data binding mechanisms of Windows Forms and WPF. Here’s a very simple example:
public class Person : INotifyPropertyChanged { private string m_firstName; private string m_lastName; public Person() : base() { } public event PropertyChangedEventHandler PropertyChanged; public string FirstName { get { return m_firstName; } set { if (!string.Equals(m_firstName, value, StringComparison.Ordinal)) { m_firstName = value; OnPropertyChanged(new PropertyChangedEventArgs("FirstName")); } } } public string LastName { get { return m_lastName; } set { if (!string.Equals(m_lastName, value, StringComparison.Ordinal)) { m_lastName = value; OnPropertyChanged(new PropertyChangedEventArgs("LastName")); } } } protected virtual void OnPropertyChanged(PropertyChangedEventArgs e) { PropertyChangedEventHandler handler = PropertyChanged; if (handler != null) { handler(this, e); } } }
That’s all there is to it. Views that data bind to the Person object will automatically update when either the FirstName or LastName properties are changed. You can download sample WPF and Windows Forms applications demonstrating this using the link at the bottom of this post. Both applications are very simple – they contain a list control that is data bound to a collection of Person objects and two text boxes that are data bound to the FirstName and LastName properties of the selected item in the list control. The screenshot below is from the WPF application.
Now, there’s nothing terribly wrong with the Person object in this example but you’ll probably have more than two properties on your data model objects and it can become cumbersome writing similar code for each property setter. In Part II we’ll look at reducing this burden.
0 comments:
Post a Comment