Mark Uivari
Mark Uivari

Reputation: 295

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!";
    }

Upvotes: 3

Views: 9360

Answers (3)

Fables Alive
Fables Alive

Reputation: 2808

When databinding via Itemsource not refresh even source is modified this may solve refresh problem

Upvotes: -2

Michael Mairegger
Michael Mairegger

Reputation: 7301

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.

Upvotes: 14

wuerzelchen
wuerzelchen

Reputation: 252

Why do you not use it like this when you're in code behind anyways (I'm not sure about .Text maybe it's .Content just try it out):

<TextBlock x:Name="txtSomeTextBlock/>

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

private void Button_Click(object sender, RoutedEventArgs e)
{
    txtSomeTextBlock.Text = "This is the changed text!";
}

Upvotes: 0

Related Questions