数据绑定工作,你需要有一个属性,不仅仅是一个简单的成员变量。而你的Datacontext类必须实现INotifyPropertyChanged接口。
public class MyDataContext : INotifyPropertyChanged
private string number;
public string Number {
get {return number;}
set {number = value; NotifyPropertyChanged("Number");}
}
// implement the interface of INotifyPropertyChanged here
// ....
}
public class MainWindow() : Window
{
private MyDataContext ctx = new MyDataContext();
//This thing is out of my head, so please don't nail me on the details
//but you should get the idea ...
private void InitializeComponent() {
//...
//... some other initialization stuff
//...
this.Datacontext = ctx;
}
}
你可以使用这个在XAML如下
<Window ...>
<!-- some other controls etc. -->
<TextBlock Text={Binding Number} />
<!-- ... -->
</Window>
为什么不使用['TextBlock.Text'](http://msdn.microsoft.com/en-us/library/ system.windows.controls.textblock.text(v = vs.110).aspx)属性 – Habib
我已经使用过了,但是在字符串的每次更改下编写它非常麻烦。 – Cristian126
为你的字符串定义一个私有属性,它是setter,将值设置为你的'TextBlock.Text',这是你可以模仿它的。 – Habib