日期:2014-05-18  浏览次数:20844 次

WPF简单绑定,新手,求解
刚开始学WPF,现看到绑定,在对一个textbox的text和类的一个字段的绑定遇到了一个问题,界面就是一个textbox和一个buttom
stu.Name改变可以textbox1.text,但是textbox1.text改变不可以改变stu.Name,求解
C# code

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; } }
    }
}





------解决方案--------------------
C# code

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}"