Search code examples
c#xamlwindows-store-appsmicrosoft-metrowinrt-xaml

Binding variable with TextBlock


I have my XAML code (inside a Page of the standard blank page template) as

<Grid>
  <TextBlock x:Name="tbBindingBlock">
</Grid>

And I have an int named iTestBindingin the code-behind. Is there a simple (since I'm only binding one variable and not a collection) way of binding the two together so that the latest value of iTestBinding (which keeps getting changed from the code-behind) is always displayed inside tbBindingBlock ?


Edit : The code behind is pretty short :

public sealed partial class MainPage : Page
{
    public int iTestBinding=0;

Solution

  • you can bind your value directly using the below code

    <TextBlock x:Name="tbBindingBlock" Text="{Binding iTestBinding}">
    

    keep your value to bind as a property in code behind like this

          public int iTestBinding{ get; set; }
    

    and set the datacontext in page loaded event like this

          this.DataContext = this;
    

    if you want to update the value on button click and to be reflected in UI, you need to implement the PropertyChangedEventHandler.

     public event PropertyChangedEventHandler PropertyChanged;
     private void RaisePropertyChanged(string propertyName)
        {
            // take a copy to prevent thread issues
            PropertyChangedEventHandler handler = PropertyChanged;
            if (handler != null)
            {
                handler(this, new PropertyChangedEventArgs(propertyName));
            }
        }
    

    call RaisePropertyChanged("changed property name") where-ever you updated the value of the property.

    Its better to keep a custom get set for the property so that we can call this method from the setter.for example

        private string myText;
        public string MyText { 
            get {
                return myText;
        }
            set {
                myText = value;
                RaisePropertyChanged("MyText");
            }
        }