Does anyone know how to assign a string to a textblock?
e.x. I have a string, with variable content, and a textBlock. The text of the textBlock should always match the content of the string.
string number;
public MainPage()
{
//the textBlock text should now be "1"
number = "1";
//the textBlock text should now be "second"
number = "second";
}
I tryed to do this automatically with bindings, but I couldn't find a solution.
regards, Cristian
For Databinding to work you need to have a a Property and not just a simple member variable. And your Datacontext class has to implement the INotifyPropertyChanged Interface.
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;
}
}
And you may use this in the XAML as following
<Window ...>
<!-- some other controls etc. -->
<TextBlock Text={Binding Number} />
<!-- ... -->
</Window>