WPF: Changes in binding elements

In .Net Framework 4.5, Microsoft introduces INotifyPropertyChanged interface.  It notifies clients that a property value has changed.

This is especially useful for updating binding clients.

The INotifyPropertyChanged exposes the PropertyChanged member.

The following example gives a good illustration of this interface.

To illustrate this example differently, we will create a class file called Person.cs.  In the Solution Explorer window, right-click on the project node and select Add and then Class.

add_class

So now we will have 3 main files in this program.  MainWindow.xaml, MainWindow.xaml.cs and Person.cs.

MainWindow.xaml
<Window x:Class="SingleObject1.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="MainWindow" Height="350" Width="525">
    <StackPanel>
        <TextBlock Text="{Binding Name}"/>
        <TextBlock Text="{Binding Age}" />
        <Button Margin="180,180,160,100" Click="OnChange">Change</Button>
    </StackPanel>
</Window>

MainWindow.xaml.cs
using System.Windows;

namespace SingleObject1
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        Person person = new Person { Name = "Miley Cyrus", Age = 21 };

        public MainWindow()      
        {
            InitializeComponent();
            DataContext = person;
        }

        private void OnChange(object sender, RoutedEventArgs e)
        {
            person.Age++;
        }
    }
}

Person.cs
using System.ComponentModel;

namespace SingleObject1
{
    public class Person : INotifyPropertyChanged
    {

        public event PropertyChangedEventHandler PropertyChanged;

        int _age;

        public string Name { get; set; }
        public int Age
        {
            get { return _age; }
            set
            {
                _age = value;
                var pc = PropertyChanged;
                if (pc != null)
                    pc(this, new PropertyChangedEventArgs("Age"));
            }
        }
       
    }
}

As you click on the button Change, the age of Miley Cyrus will increment one by one.

propertychanged

 

 

Series Navigation<< WPF: Defining an instance in XAML
WPF: Specify the property to display in ListBox >>