用通俗的代码解决
首先创建一个class类
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace WpfMvvm.ViewModels
{
class student
{
private string name;
public string Name
{
get { return name; } set { name = value; }
}
}
}
引用空间system.ComponentModel,添加端口
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ComponentModel;
namespace WpfMvvm.ViewModels
{
class student:INotifyPropertyChanged
{
private string name;
public string Name
{
get { return name; }
set {
name = value;
if (PropertyChanged != null)
{
this.PropertyChanged.Invoke(this, new PropertyChangedEventArgs("Name"));
}
}
}
public event PropertyChangedEventHandler PropertyChanged;
}
}
添加一个xmal文件,student.xmal
/// <summary>
/// Student.xaml 的交互逻辑
/// </summary>
public partial class Student : Window
{
student stu;
public Student()
{
stu = new student();
InitializeComponent();
Binding bind = new Binding();
bind.Source = stu;
bind.Path = new PropertyPath("Name");
BindingOperations.SetBinding(this.textBox1,TextBox.TextProperty, bind);
}
private void button1_Click(object sender, RoutedEventArgs e)
{
stu.Name += "name";
}
}
}
有种简单的方法是用
this.textBox1.SetBinding(TextBox.TextProperty,new Binding("Name"){Source=stu=new student()});