using System; using System.Collections.Generic; using System.ComponentModel; 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 Wpf数据绑定 { /// <summary> /// MainWindow.xaml 的交互逻辑 /// </summary> public partial class MainWindow : Window { private Person p1 = new Person(); public MainWindow() { InitializeComponent(); } private void Window_Loaded(object sender, RoutedEventArgs e) { p1.Age = 20; p1.Name = "梁朝伟"; grid1.DataContext = p1; } private void button1_Click(object sender, RoutedEventArgs e) { MessageBox.Show(p1.Age.ToString()+p1.Name); } private void button2_Click(object sender, RoutedEventArgs e) { p1.Age++; p1.Name = "金城武"; } } class Person:INotifyPropertyChanged { public event PropertyChangedEventHandler PropertyChanged; private int age; private string name; public string Name { get { return name; } set { this.name = value; if (PropertyChanged != null) { PropertyChanged(this, new PropertyChangedEventArgs("Name")); } } } public int Age { get { return age; } set { this.age= value; if (PropertyChanged != null) { PropertyChanged(this, new PropertyChangedEventArgs("Age")); } } } } }
同时在前台在想要绑定的控件里写如:Text=“{Binding Name}”
一般不直接写textbox_1.Text=p1.Name 是为了避免直接操作控件。