简体   繁体   English

UWP中的数据绑定不会刷新

[英]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. 我正在尝试将xaml中TextBlock的'Text'属性绑定到全局字符串,但是当我更改字符串时,TextBlock的内容不会改变。 What is that I'm missing? 我错过了什么?

My xaml: 我的xaml:

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

My C#: 我的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!";
    }

The default binding mode for x:Bind is OneTime rather then OneWay that was de-facto the default for Binding . x:Bind的默认绑定模式是OneTime而不是OneWay ,它实际上是Binding的默认值。 Furthermore text is private . 此外, textprivate To have a working binding you need to have a public property . 要拥有一个有效的绑定,您需要拥有一个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. 另外,在Text的setter中引发PropertyChanged很重要。

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): 当你在代码背后时,你为什么不这样使用它(我不确定.Text也许它是.Content只是尝试一下):

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

当通过Itemsource的数据绑定不刷新甚至源被修改时, 这可以解决刷新问题

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM