Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Data Binding in UWP doesn't refresh

I'm trying to bind the 'Text' property of my TextBlock in xaml to a global string, but when I change the string the TextBlock's content doesn't change. What is that I'm missing?

My xaml:

<StackPanel>
        <Button Content="Change!" Click="Button_Click" />
        <TextBlock Text="{x:Bind text}" />
</StackPanel>

My C#:

    string text;
    public MainPage()
    {
        this.InitializeComponent();
        text = "This is the original text.";
    }

    private void Button_Click(object sender, RoutedEventArgs e)
    {
        text = "This is the changed text!";
    }
like image 881
Mark Uivari Avatar asked Jul 19 '26 05:07

Mark Uivari


1 Answers

The default binding mode for x:Bind is OneTime rather then OneWay that was de-facto the default for Binding. Furthermore text is private. To have a working binding you need to have a public property.

<TextBlock Text="{x:Bind Text , Mode=OneWay}" />

And in code-behind

private string _text;
public string Text
{ 
    get { return _text; }
    set
    {
        _text = value;
        NotifyPropertyChanged("Text");
    }

Plus it is important to raise PropertyChanged in the setter of Text.

like image 121
Michael Mairegger Avatar answered Jul 20 '26 18:07

Michael Mairegger



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!