要使后台类对象的属性值发生改变,通知在“界面与之绑定的控件值”,需要实现INotitypropertyChanged接口。
INotifyPropertyChanged 接口用于通知客户端(通常是绑定客户端)属性值已更改。
INotifyPropertyChanged是.net内置的接口,数据绑定DataContext是否实现了INotityPropertyChanged接口,如果实现了,就会监听PropertyChanged得知属性的变化。
如果要求后台对象的值发送改变,界面的值也跟着变,则需要实现INotityPropertyChanged接口,并且在对象属性值变化后触发事件。
如果说后台对象的值会不变,则没有必要实现这个接口
前端设计 MainWindow.xaml
<Window x:Class="BindDataContextDemo.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="250" Width="300" >
<StackPanel HorizontalAlignment="Center" VerticalAlignment="Center">
<TextBlock Text="用户名" FontSize="15"/>
<TextBox Text="{Binding UserName,Mode=TwoWay,UpdateSourceTrigger=PropertyChanged}" Width="180" Height="30" FontSize="15" Margin="10"/>
<TextBlock Text="年龄" FontSize="15"/>
<TextBox Text="{Binding UserAge,Mode=TwoWay,UpdateSourceTrigger=PropertyChanged}" Width="180" Height="30" FontSize="15" Margin="10"/>
<Button Content="读取数据更新界面" Width="180" Height="40" FontSize="15" Click="Update_Click"/>
</StackPanel>
</Window>
后台逻辑 MainWindow.xaml.cs
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
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 BindDataContextDemo
{
/// <summary>
/// MainWindow.xaml 的交互逻辑
/// </summary>
public partial class MainWindow : Window, INotifyPropertyChanged
{
public MainWindow()
{
this.DataContext = this;
InitializeComponent();
}
private string userName = "张三";
public string UserName
{
get { return userName; }
set
{
userName = value;
OnPropertyChanged("UserName");
}
}
private int userAge = 0;
public int UserAge
{
get { return userAge; }
set
{
userAge = value;
OnPropertyChanged("UserAge");
}
}
public event System.ComponentModel.PropertyChangedEventHandler PropertyChanged;
protected void OnPropertyChanged(string propertyName)
{
if (PropertyChanged != null)
{
PropertyChanged(this, new System.ComponentModel.PropertyChangedEventArgs(propertyName));
}
}
private void Update_Click(object sender, RoutedEventArgs e)
{
UserName = "常昊灵";
UserAge = 100;
}
}
}
软件运行结果展示
点击按钮,数据变化
之前项目中,忘记继承INotifyPropertyChanged接口,导致数据不变化,以其文章记录,方便后期开发出现同样问题,快速找到原因。