wpf後臺程式碼資料繫結
阿新 • • 發佈:2019-02-06
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 WpfApplication2 { /// <summary> /// MainWindow.xaml 的互動邏輯 /// </summary> public partial class MainWindow : Window { Student stu; public MainWindow() { InitializeComponent(); // 準備資料來源 stu = new Student() { Name = "小明" }; // 準備Binding Binding binding = new Binding() { Source = stu// 資料來源 , Path = new PropertyPath("Name")// 需繫結的資料來源屬性名 , Mode = BindingMode.TwoWay// 繫結模式 , UpdateSourceTrigger = UpdateSourceTrigger.PropertyChanged }; // 連線資料來源與繫結目標 BindingOperations.SetBinding( txt// 需繫結的控制元件 , TextBox.TextProperty// 需繫結的控制元件屬性 , binding); // 簡寫 //txt.SetBinding(TextBox.TextProperty, new Binding("Name") //{ // Source = stu, // Mode = BindingMode.TwoWay //}); } private void Button_Click(object sender, RoutedEventArgs e) { MessageBox.Show(stu.Name); } } public class Student : INotifyPropertyChanged { private string name; public string Name { get { return name; } set { name = value; if (PropertyChanged != null) { PropertyChanged(this, new PropertyChangedEventArgs("Name")); } } } public event PropertyChangedEventHandler PropertyChanged; } }