Binding在業界的使用一直是音譯而來的,稱為"Binding"。Binding的源是邏輯數據對象,目標則是UI層上面的控件對象。數據通過Binding送達UI層,被UI層展示出來,也就完成了數據驅動UI的過程了。
下面通過一個很簡單的列子來引入我們最原始的Binding:
<Window x:Class="BindingTest.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:BindingTest" mc:Ignorable="d" Title="MainWindow" Height="100" Width="400"> <StackPanel> <TextBox Name="MyTextBlock" BorderBrush="Black" Margin="3"/> <Button Content="Add Age" Margin="3" Click="Button_Click"/> </StackPanel> </Window>
Binding有一種自動機制,就是當后台綁定的屬性值發生改變時,會自動通知給UI元素,怎么樣才能讓屬性具備這樣的能力呢,其實只需要在屬性set的時候去觸發PropertyChanged事件。這個事件不需要我們聲明,只需要我們去實現INotifyPropertyChanged接口。實現了此接口的學生類如下:
using System; using System.Collections.Generic; using System.ComponentModel; using System.Linq; using System.Text; using System.Threading.Tasks; namespace BindingTest.Models { public class Student : INotifyPropertyChanged { public event PropertyChangedEventHandler PropertyChanged; public int _age; public int Age { get { return this._age; } set { if (value != 0) { this._age = value; PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(nameof(Age))); } } } } }
最終在窗體的后台代碼中:
namespace BindingTest { /// <summary> /// MainWindow.xaml 的交互邏輯 /// </summary> public partial class MainWindow : Window { Student studen; public MainWindow() { InitializeComponent(); studen = new Student(); Binding binding = new Binding(); binding.Source = studen; binding.Path = new PropertyPath("Age"); BindingOperations.SetBinding(this.MyTextBlock, TextBox.TextProperty, binding);//設置目標對象的屬性和源的綁定 } private void Button_Click(object sender, RoutedEventArgs e) { studen.Age += 1;//改變對象,頁面中textbox中數據也會變化 } } }
1綁定的源和路徑
1.1 控件作為binding的源
Ui元素之間有時候需要進行一些關聯效果可以利用Binding在控件之間建立關聯,下面的代碼就是將TextBlock的text和Slider(滑動條)的value進行了關聯。運行下面這段代碼就會發現當Slider滑動的時候,TextBlock中的值會隨之改變。
<Window x:Class="BindingTest.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:BindingTest" mc:Ignorable="d" Title="MainWindow" Height="100" Width="400"> <StackPanel> <Slider Value="0" Name="slider1" Minimum="0" Maximum="100"></Slider> <TextBlock Text="{Binding ElementName=slider1,Path=Value}" Margin="3"></TextBlock> </StackPanel> </Window>
可以通過設置Binding的Mode來設置數據流向,一般有TwoWay,OneWay,OnTime,OneWayToSource以及Default,如果不設置就是Default,如果你的目標控件是用戶可編輯的就是雙向的,比如TextBox如果是不可編輯的,那么就是單向的,比如TextBlock。