Updated on Kisan Patel
This post will explain you how to bind single object in WPF and also learn how to implement The INotifyPropertyChanged
interface in WPF application.
The INotifyPropertyChanged
interface is used to notify clients, typically binding clients, that a property value has changed using PropertyChangedEventHandler
.
For example, consider a Student object with a property called Age. To provide generic property-change notification, the Student type implements the INotifyPropertyChanged interface and raises a PropertyChanged event when Age is changed.
Lets create new WPF application and name it “WPFNotifyDemo”.
Next, Add below line of code that contain two textboxes in MainWindow.xaml file.
<Grid> <Grid.RowDefinitions> <RowDefinition Height="30" /> <RowDefinition Height="30" /> <RowDefinition Height="30" /> </Grid.RowDefinitions> <Grid.ColumnDefinitions> <ColumnDefinition Width="100" /> <ColumnDefinition Width="200" /> </Grid.ColumnDefinitions> <Label Grid.Row="0" Grid.Column="0" Content="Name: " FontSize="16"/> <TextBox Grid.Row="0" Grid.Column="1" Text="{Binding Name}" /> <Label Grid.Row="1" Grid.Column="0" Content="Age: " FontSize="16"/> <TextBox Grid.Row="1" Grid.Column="1" Text="{Binding Age}" /> </Grid>
Now, add Student class:
public class Student { public string Name { get; set; } public int Age { get; set; } }
Next, In the MainWindow
constructor, create an instance of Student with dummy data then set the DataContext
property to this:
Student _student = new Student { Name = "Kisan Patel", Age = 24 }; public MainWindow() { InitializeComponent(); DataContext = _student; }
Run the WPF application. The property values are reflected in the TextBox
because the DataContext
is the default source for the binding.
Next, add one button with a Click event handler as shown in below code:
MainWindow.xaml
<Button Name="ChangeAge" Content="Change Age" Grid.Row="2" Grid.Column="1" Click="ChangeAge_Click" />
MainWindow.xaml.cs
private void ChangeAge_Click(object sender, RoutedEventArgs e) { _student.Age++; }
Now, Run the application and click “Change Age” button. Notice the displayed Age doesn’t change.
Now, lets implement INotifyPropetryChanged
interface. you need to open Student.cs and make the Student class implement the INotifyPropetryChanged
interface:
INotifyPropertyChanged
Interface defined in System.ComponentModel
Class. so you need to add the below using statement:
using System.ComponentModel;
Next, we need to raise the event Property when a property changes. So modify Student class as shown below code:
public class Student : INotifyPropertyChanged { public string Name { get; set; } int _age; public int Age { get { return _age; } set { _age = value; var pc = PropertyChanged; if (pc != null) pc(this, new PropertyChangedEventArgs("Age")); } } public event PropertyChangedEventHandler PropertyChanged; }
Now, Run the application and click the “Change Age” button. The age is changed and displayed correctly in the TextBox.