转载位置:
https://www.cnblogs.com/lizhiqiang0204/p/12469166.html
源码下载地址:https://github.com/lizhiqiang0204/Static-and-non-static-property-changes
程序集整体结构如下
MainWindow.xaml布局如下
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="*"/>
<RowDefinition Height="*"/>
</Grid.RowDefinitions>
<StackPanel >
<Label Content="{Binding myClassA.myString}"/>
</StackPanel>
<StackPanel Grid.Row="1" >
<StackPanel.DataContext>
<!--该Grid所有绑定都是绑定到ClassA里面的属性-->
<local:ClassA/>
</StackPanel.DataContext>
<Label Content="{Binding myLabel}"/>
<!--绑定到ClassA里面myLabel字符串属性-->
<Button x:Name="myButton" Content="ButtonA" Click="ButtonA_Click" />
<!--在MainWindow.xaml.cs后台文件中执行按键单击事件,单击事件就是改变ClassA中的myLabel属性同时在界面上显示出更改的信息-->
</StackPanel>
</Grid>
ClassA.cs如下
using System;
using System.ComponentModel;
namespace WpfApp1
{
public class ClassA : INotifyPropertyChanged
{
private static string label = "静态字符";
public static string myLabel
{
get { return label; }
set
{
label = value;
StaticPropertyChanged?.Invoke(null, new PropertyChangedEventArgs(nameof(myLabel)));//异步更新静态属性
}
}
public static event EventHandler<PropertyChangedEventArgs> StaticPropertyChanged;//静态事件处理属性更改
private string str = "非静态字符";
public string myString
{
get { return str; }
set
{
str = value;
OnPropertyChanged("myString");//异步更新非静态属性
}
}
public event PropertyChangedEventHandler PropertyChanged;//非静态属性更改
protected virtual void OnPropertyChanged(string propertyName)
{
if (PropertyChanged != null)
PropertyChanged.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
}
}
MainWindow.xaml.cs如下
using System.Windows;
namespace WpfApp1
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
public ClassA myClassA { get; set; } = new ClassA();
public MainWindow()
{
InitializeComponent();
DataContext = this;
}
private void ButtonA_Click(object sender, RoutedEventArgs e)
{
ClassA.myLabel = "更改绑定静态字符";
myClassA.myString = "更改绑定非静态字符串";
}
}
}
单击按键之前界
单击之后