日期:2014-05-18 浏览次数:20844 次
namespace WpfApplication1 { /// <summary> /// Interaction logic for MainWindow.xaml /// </summary> public partial class MainWindow : Window { private Student stu; public MainWindow() { InitializeComponent(); stu = new Student(); Binding binding = new Binding(); binding.Source = stu; binding.Path = new PropertyPath("Name"); BindingOperations.SetBinding(this.textBox1, TextBox.TextProperty, binding); } private void button1_Click(object sender, RoutedEventArgs e) { stu.Name += "Name"; } } class Student { private string name; public string Name { get { return name; } set { name = value; } } } }
1. 你要继承INotifyPropertyChanged 然后实现接口方法: #region INotifyPropertyChanged Members private void NotifyPropertyChanged(string Propertyname) { PropertyChangedEventHandler handler = PropertyChanged; if (PropertyChanged != null) { foreach(PropertyChangedEventHandler e in handler.GetInvocationList()) e(this, new PropertyChangedEventArgs(Propertyname)); } } public event PropertyChangedEventHandler PropertyChanged; #endregion 2. 在你要绑定的property这样做 private string _myProperty; public string myProperty { get { return _myProperty; } set { _myProperty= value; NotifyPropertyChanged("myProperty"); } } 3.然后在页面上要设值的地方这样绑定 Scr="{Binding myProperty, Mode=Twoway}"