WPF實現簡單的資料繫結
阿新 • • 發佈:2019-01-10
建立資料來源類
首先建立一個作為資料來源來使用,這裡建立的類需要實現System.ComponentModel名稱空間中的INotifyPropertyChanged介面。當為Binding設定了資料來源之後,Binding就會自動偵聽來自這個介面的PropertyChanged事件。
class Student:INotifyPropertyChanged
{
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"));
}
}
}
}
UI
<Window x:Class="WpfApplication1.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:WpfApplication1" mc:Ignorable="d" Title="MainWindow" Height="350" Width="525"> <StackPanel> <TextBox x:Name="textBoxName" BorderBrush="Black" Margin="5"/> <Button Content="Change" Margin="5" Click="Button_Click"/> </StackPanel> </Window>
使用這個介面的目的就是演示,當點選按鈕後修改類中的值,UI會不會發生變化
資料來源和UI元素連線
public partial class MainWindow : Window
{
Student stu;
public MainWindow()
{
InitializeComponent();
//1----------------------------------------
//準備資料來源
stu = new WpfApplication1.Student();
//準備Binding
Binding binding = new Binding();
binding.Source = stu;
binding.Path = new PropertyPath("Name");
//使用Binding連線資料來源與Binding目標
BindingOperations.SetBinding(this.textBoxName, TextBox.TextProperty, binding);
//2----------------------------------------
this.textBoxName.SetBinding(TextBox.TextProperty, new Binding("Name")
{
Source = stu = new WpfApplication1.Student()
});
}
private void Button_Click(object sender, RoutedEventArgs e)
{
stu.Name += "Name";
}
}
BindingOperations.SetBinding三個引數
第一個引數用於指定Binding目標
第二個引數用於Binding指明把資料送達目標的哪個屬性
第三個引數指定使用那個Binding例項將資料來源與目標關聯起來