1.概要
2.代码
2.1 xaml
<Window x:Class="WpfApp3.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:WpfApp3"
mc:Ignorable="d"
Title="MainWindow" Height="200" Width="300">
<StackPanel>
<TextBox Text="{Binding Path=Zhi}"></TextBox>
<Button Content="Button" Click="Button_Click"/>
</StackPanel>
</Window>
2.2 code
using System.ComponentModel;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
namespace WpfApp3
{
/// <summary>
/// Interaction logic for MainWindow.xaml
///
/// </summary>
public partial class MainWindow : Window
{
A a = new A();
public MainWindow()
{
InitializeComponent();
this.DataContext = a;
}
private void Button_Click(object sender, RoutedEventArgs e)
{
this.a.Zhi = "新的值";
}
}
class A:INotifyPropertyChanged
{
public A()
{
this.Zhi = "旧的值";
}
private String _zhi;
public String Zhi {
set { _zhi = value; OnPropertyChanged(nameof( Zhi));
}
get {
return _zhi;
}
}
public event PropertyChangedEventHandler? PropertyChanged;
private void OnPropertyChanged(String name)
{
if (PropertyChanged != null) {
PropertyChanged.Invoke(this, new PropertyChangedEventArgs(name));
}
}
}
}
3.实验结果