WPF 之 INotifyPropertyChanged 接口的使用 (一)
一、INotifyPropertyChanged 的基本概念
INotifyPropertyChanged 的作用:通知客户端属性值已经更改。详细信息见:INotifyPropertyChanged 接口(Microsoft)。实现接口如下图:
二、优化 INotifyPropertyChanged 接口实现
优化后的 INotifyPropertyChanged 接口实现类如下所示:
1 class NofifyPropertyChanged : INotifyPropertyChanged
2 {
3 public event PropertyChangedEventHandler PropertyChanged;
4 protected void SetProperty<T>(ref T prop, T value, [CallerMemberName] string propertyName = null)
5 {
6 if (EqualityComparer<T>.Default.Equals(prop, value) == false)
7 {
8 prop = value;
9 OnPropertyChanged(propertyName);
10 }
11 }
12
13 public virtual void OnPropertyChanged(string propertyName)
14 {
15 PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
16 }
17 }
例如与 UI 绑定的 ViewModel 如下所示:
class Window1VM : NofifyPropertyChanged
{
private string _name;
public string Name
{
get => _name;
set => SetProperty(ref _name, value);
}
}
三、ViewModel 与 UI 界面绑定
UI 界面如下图所示:
XAML 绑定代码如下图:
1 <Window x:Class="UI.Window1"
2 xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
3 xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
4 xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
5 xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
6 xmlns:local="clr-namespace:UI"
7 d:DataContext="{d:DesignInstance local:Window1VM}"
8 mc:Ignorable="d"
9 Title="Window1" Height="250" Width="300">
10 <StackPanel Margin="10" >
11 <TextBlock Text="Name Value(Read and Write):"></TextBlock>
12 <TextBox Margin="0,5,0,5" Height="50" VerticalContentAlignment="Center" BorderBrush="BlueViolet" BorderThickness="3" Text="{Binding Path=Name,Mode=TwoWay,UpdateSourceTrigger=PropertyChanged}"></TextBox>
13 <TextBlock Text="Name Value(Only Read):"></TextBlock>
14 <TextBox Margin="0,5,0,5" Height="50" VerticalContentAlignment="Center" BorderBrush="BlueViolet" BorderThickness="3" Text="{Binding Path=Name,Mode=OneWay}"></TextBox>
15 </StackPanel>
16 </Window>
在 Window1 界面的后置代码中初始化 ViewModel ,如下图所示:
运行程序后,两个文本框绑定的内容正常显示,当我们改变第一个文本框内的内容时,第二个文本框的内容同步发生变化,这表示,Window1VM 的属性 “Name” 和 Window1.xaml 中文本框的 “Text”属性绑定成功!