-5

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

Kirk Roybal
  • 17,273
  • 1
  • 29
  • 38
Matt126
  • 997
  • 11
  • 25

1 Answers1

2

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>
derpirscher
  • 14,418
  • 3
  • 18
  • 35
  • Note that for this to work, you need to assign to "Number" not "number". Showing the binding string setup would also make this a much better answer. +1 for the correct approach though. – BradleyDotNET Jul 03 '14 at 18:30
  • Thanks for your comment. I edited my answer according to your suggestion. It's not the prettiest solution, but one should get the idea. – derpirscher Jul 03 '14 at 18:42