源碼下載地址: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 = "更改綁定非靜態字符串"; } } }
單擊按鍵之前界
單擊之后