
在WPF中Binding对象是一根连接绑定目标和数据源的桥梁,任何一方变化都会通过Binding来通知。.
<Window x:Class="Example_03.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:Example_03" mc:Ignorable="d" Title="MainWindow" Height="200" Width="400"><Window.Resources><local:Student x:Key="StudentSource" StuName="张三"></local:Student></Window.Resources><Grid><Grid.RowDefinitions><RowDefinition></RowDefinition><RowDefinition></RowDefinition></Grid.RowDefinitions><Grid.ColumnDefinitions><ColumnDefinition Width="0.3*"></ColumnDefinition><ColumnDefinition></ColumnDefinition></Grid.ColumnDefinitions><TextBlock Text="学生姓名:" Grid.Row="0" Grid.Column="0" HorizontalAlignment="Right" VerticalAlignment="Center"/><TextBox Grid.Row="0" Grid.Column="1" Height="30" Width="200"Text="{Binding Source={StaticResource StudentSource},Path=StuName,UpdateSourceTrigger=PropertyChanged}"/><TextBlock Text="学生姓名:" Grid.Row="1" Grid.Column="0" HorizontalAlignment="Right" VerticalAlignment="Center"/><TextBlock Grid.Row="1" Grid.Column="1" Height="30" Width="200"Text="{Binding Source={StaticResource StudentSource},Path=StuName}"/></Grid></Window>
public class Student : INotifyPropertyChanged{private string _stuname;public Student() { }public Student(string value){_stuname = value;}public string StuName{get { return _stuname; }set{_stuname = value;OnPropertyChanged("StuName");}}/// <summary>/// 定义事件/// </summary>public event PropertyChangedEventHandler PropertyChanged;//创建 OnPropertyChanged 方法触发事件protected void OnPropertyChanged(string _stuname){var handler = PropertyChanged;handler?.Invoke(this, new PropertyChangedEventArgs(_stuname));}}
Binding 的工作原理:
Source 表示绑定数据源. Path 绑定的属性. UpdateSourceTrigger触发事件通知数据源
Mode 绑定的方向.如下:OneWay、TwoWay、OneWayToSource
Oneway 表示数据源发生变化时,通知目标属性,但绑定目标改变不会改变绑定源
TwoWay 表示任何一方发生变化都会通知对方
OneWayToSource 表示目标属性发生变化时通知数据源
UpdateSourceTrigger=PropertyChanged 表示属性的值发生变化时,数据源会更新

INotifyPropertyChanged接口说明:
OneWay:绑定源实体类没有实现INotifyPropertyChanged接口,数据源发生变化时,绑定目标是不会发生变化,所以我们数据源实体需要实现INotifyPropertyChanged接口

这里引出一个概念依赖属性:Windows Presentation Foundation (WPF) 提供了一组服务,这些服务可用于扩展CLR)属性的功能。这些服务通常统称为 WPF 属性系统。由 WPF 属性系统支持的属性称为依赖项属性。依赖属性是一种可以自己没有值,并能通过使用Binding从数据源获得值的属性(通俗的讲,就是依赖在别的属性上)依赖属性是WPF基础关键概念,包含动画、属性值继承、数据绑定和样式都使用依赖属性,下节我们将介绍依赖属性。