文章出處
文章列表
1)數據源
添加一個Student類:
(Binding是一種自動機制,當值變化后屬性要有能力通知Binding,讓Binding把變化傳遞給UI元素。方法是在屬性set語句中激發一個PropertyChanged事件。這個事件不用我們聲明,我們要做到的是讓作為數據源的類實現System.ComponentModel名稱空間中的INotifyPropertyChanged接口。當為Binding設置了數據源后,Binding就會自動監聽來自這個接口的PropertyChanged事件。)
using System; using System.Collections.Generic; using System.ComponentModel; using System.Linq; using System.Text; namespace TestBinding { class Student:INotifyPropertyChanged//實現這個接口,讓Binding自動監聽 { public event PropertyChangedEventHandler PropertyChanged; private string name; public string Name { get { return name; } set { name = value; //激發事件 if (this.PropertyChanged != null) { this.PropertyChanged.Invoke(this, new PropertyChangedEventArgs("Name")); } } } } }
或者:
using System; using System.Collections.Generic; using System.ComponentModel; using System.Linq; using System.Text; namespace TestBinding { class Student:INotifyPropertyChanged//實現這個接口,讓Binding自動監聽 { public event PropertyChangedEventHandler PropertyChanged; private string name; public string Name { get { return name; } set { name = value; //激發事件 PropertyChangedEventHandler handler = PropertyChanged; if (this.PropertyChanged != null) { //this.PropertyChanged.Invoke(this, new PropertyChangedEventArgs("Name")); handler(this, new PropertyChangedEventArgs("Name")); } } } } }
2)編寫前臺代碼:
XAML:
<Window x:Class="TestBinding.MainWindow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" Title="MainWindow" Height="110" Width="300"> <Grid> <StackPanel> <TextBox x:Name="textBoxName" BorderBrush="Black" Margin="5"></TextBox> <Button Content="Add Age" Margin="5" Click="Button_Click"></Button> </StackPanel> </Grid> </Window>
3)使用Binding把數據源和UI元素連接起來
C#:
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 TestBinding { /// <summary> /// MainWindow.xaml 的交互邏輯 /// </summary> public partial class MainWindow : Window { Student stu; public MainWindow() { InitializeComponent(); /* //準備數據源 stu = new Student(); //準備Binding Binding binding = new Binding(); binding.Source = stu; binding.Path = new PropertyPath("Name");//為Binding指定訪問路徑 //使用Binding連接數據源與Binding目標 BindingOperations.SetBinding(textBoxName, TextBox.TextProperty, binding); */ //以上三合一的做法: this.textBoxName.SetBinding(TextBox.TextProperty, new Binding("Name") { Source = stu = new Student() }); //this.textBoxName.SetBinding(TextBox.TextProperty, new Binding() { Source = stu = new Student(),Path=new PropertyPath("Name") }); } private void Button_Click(object sender, RoutedEventArgs e) { stu.Name += "Name"; } } }
截圖:
文章列表
全站熱搜