C#_wpf_userinput_数据绑定_后台对象改变,界面数据也变化

时间:2021-01-18 22:15:34
<!--MainWindow.xaml-->
<Window x:Class="UserStore.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="350" Width="525" Loaded="Window_Loaded">
<Grid>
<!--数据绑定 Text-->
<TextBox Height="23" Text="{Binding Name}" HorizontalAlignment="Left" Margin="50,22,0,0" Name="txtName" VerticalAlignment="Top" Width="155" />
<TextBox Height="23" Text="{Binding Age}" HorizontalAlignment="Left" Margin="50,70,0,0" Name="txtAge" VerticalAlignment="Top" Width="155" />
<Button Content="年龄自增" Height="23" HorizontalAlignment="Left" Margin="50,164,0,0" Name="button1" VerticalAlignment="Top" Width="75" Click="button1_Click" />
</Grid>
</Window>
//MainWindow.xaml.cs
using System;
using System.Collections.Generic;
using System.Linq;
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 UserStore
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
private Person p1 = new Person(); public MainWindow()
{
InitializeComponent();
} private void Window_Loaded(object sender, RoutedEventArgs e)
{
p1.Name = "Lee";
p1.Age = 26; txtName.DataContext = p1;
txtAge.DataContext = p1;
} private void button1_Click(object sender, RoutedEventArgs e)
{
p1.Age++;
}
}
}
//Person.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ComponentModel; namespace UserStore
{
//class Person
//{
// public int Age
// {
// get;
// set;
// }
// public string Name
// {
// get;
// set;
// }
//} //内置的类,会监测INotifyPropertyChanged是否实现了,得知属性变化
class Person : INotifyPropertyChanged
{
private int age; public int Age
{
get { return age; }
set
{
this.age = value;
if (PropertyChanged != null)
{
//触发事件
PropertyChanged(this, new PropertyChangedEventArgs("Age"));
}
}
}
public string Name
{
get;
set;
} public event PropertyChangedEventHandler PropertyChanged;
}
}

C#_wpf_userinput_数据绑定_后台对象改变,界面数据也变化