BindableBase.cs
public abstract class BindableBase : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
// 调用方法 : public string Name { get => name; set { SetProperty<string>(ref name, value); } }
// 1. ref T storage:这是一个引用参数,表示要设置的属性的存储字段。ref关键字意味着如果在方法内部修改了storage,那么原始变量也会被修改。
// 2. T value:这是要设置的新值。
// 3. [CallerMemberName] string propertyName = null:这是属性的名称。
// [CallerMemberName]是一个特性,它会自动将调用该方法的属性的名称作为参数传入。
// 如果在调用SetProperty<T>()时没有提供propertyName,那么编译器会自动插入调用该方法的属性的名称。
protected virtual bool SetProperty<T>(ref T storage, T value, [CallerMemberName] string propertyName = null)
{
if (object.Equals(storage, value)) return false;
storage = value;
this.OnPropertyChanged(propertyName);
return true;
}
protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null)
{
if (PropertyChanged != null)
{
PropertyChanged.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
}
}
src\Juster.Music\MainWindow.xaml
<Window
x:Class="Juster.Music.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:local="clr-namespace:Juster.Music"
mc:Ignorable="d"
Title="MainWindow" Height="200" Width="200">
<Window.Resources>
<local:UserModel x:Key="MyDataSource"/>
</Window.Resources>
<Grid>
<Grid.RowDefinitions>
<RowDefinition></RowDefinition>
<RowDefinition></RowDefinition>
</Grid.RowDefinitions>
<StackPanel Grid.Row="0" HorizontalAlignment="Center">
<Label>Enter a Name:</Label>
<TextBox>
<Binding Source="{StaticResource MyDataSource}" Path="Name"
UpdateSourceTrigger="PropertyChanged" />
</TextBox>
</StackPanel>
<StackPanel Grid.Row="1" HorizontalAlignment="Center">
<Label>The name you entered:</Label>
<TextBlock Text="{Binding Source={StaticResource MyDataSource}, Path=Name}"/>
</StackPanel>
</Grid>
</Window>
src\Juster.Music\MainWindow.xaml.cs
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
}
UserModel.cs
public class UserModel : BindableBase
{
private string name;
// 调用父类的SetProperty()方法
public string Name { get => name; set { SetProperty<string>(ref name, value); } }
public UserModel(){ }
}