Hi All,
I am new to WPF, I created a sample project to learn INotifyPropertyChanged interface. But the UI did not update, I didn't known why.
Here is my code snippet:
XAML:
<Window x:Class="WpfNofifyApp.MainWindow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:local="clr-namespace:WpfNofifyApp" Title="INotifyPropertyChanged Sample" Height="210" Width="400"><Grid><Grid.RowDefinitions><RowDefinition Height="*"/><RowDefinition Height="*"/></Grid.RowDefinitions><GroupBox Header="Student Information:"><Grid><Grid.RowDefinitions><RowDefinition Height="*"/><RowDefinition Height="*"/></Grid.RowDefinitions><Grid.ColumnDefinitions><ColumnDefinition Width="*"/><ColumnDefinition Width="2*"/></Grid.ColumnDefinitions><TextBlock Text="Student Name:"/><TextBlock Grid.Column="1" Text="{Binding Path=Name, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"/><TextBlock Text="Student Age:" Grid.Row="1"/><TextBlock Grid.Row="1" Grid.Column="1" Text="{Binding Path=Age, UpdateSourceTrigger=PropertyChanged}"/></Grid></GroupBox><GroupBox Header="Edit Student Information:" Grid.Row="1"><Grid><Grid.RowDefinitions><RowDefinition Height="*"/><RowDefinition Height="10"/><RowDefinition Height="*"/></Grid.RowDefinitions><Grid.ColumnDefinitions><ColumnDefinition Width="*"/><ColumnDefinition Width="2*"/></Grid.ColumnDefinitions><TextBlock Text="Student Name:"/><TextBox x:Name="TxtName" Grid.Column="1" Text="{Binding Path=Name}" Height="25"/><TextBlock Text="Student Age:" Grid.Row="2"/><TextBox x:Name="TxtAge" Grid.Row="2" Grid.Column="1" Text="{Binding Path=Age}" Height="25"/></Grid></GroupBox></Grid></Window>
C# Code:
public partial class MainWindow : Window { public MainWindow() { InitializeComponent(); Student student = new Student("Meng-Lee", "24"); this.DataContext = student; } } public class Student : INotifyPropertyChanged { private string name; private string age; public event PropertyChangedEventHandler PropertyChanged; public Student( string name, string age) { this.name = name; this.age = age; } public string Name { get { return name; } set { name = value; OnPropertyChanged(Name); } } public string Age { get { return age; } set { age = value; OnPropertyChanged(Age); } } // Create the OnPropertyChanged method to raise the event protected void OnPropertyChanged(string name) { PropertyChangedEventHandler handler = PropertyChanged; if (handler != null) { handler(this, new PropertyChangedEventArgs(name)); } } }
Thanks!