【问题标题】:Data Binding in UWP doesn't refreshUWP 中的数据绑定不刷新
【发布时间】:2016-02-17 14:18:56
【问题描述】:

我正在尝试将 xaml 中 TextBlock 的“Text”属性绑定到全局字符串,但是当我更改字符串时,TextBlock 的内容不会改变。我错过了什么?

我的 xaml:

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

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

【问题讨论】:

  • 这将永远不会更新,因为您没有引发 PropertyChanged 事件。为了更新它,创建一个静态的 DTO,并在其中包含字符串。静态 Dto 需要实现 NotifyProperty 已更改。
  • 当 itemsource 不刷新时你可以试试这个解决方案:Here is Relevant Solution

标签: c# xaml win-universal-app


【解决方案1】:

x:Bind 的默认绑定模式是OneTime,而不是OneWay,这实际上是Binding 的默认值。此外textprivate。要拥有有效的绑定,您需要有一个public property

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

在代码隐藏中

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

另外,在 Text 的 setter 中引发 PropertyChanged 也很重要。

【讨论】:

  • 你实现INotifyPropertyChanged了吗?
  • 'raise PropertyChanged in the setter of Text' 你是什么意思?
  • 也许你会认为我的下一个问题很愚蠢,但我之前没有使用过 getter 和 setter。我收到 _text 和 NotifyPropertyChanged 的​​“在此上下文中不存在”错误。
  • @MarkUivari 这是因为 _text 字段不存在并且您没有实现 INotifyPropertyChanged 接口。只需创建一个字符串字段 _text 并实现接口,如我上面提供的链接所示。
  • 好吧,我花了一段时间,但我让它工作了。谢谢。
【解决方案2】:

无论如何,当您在代码中时,为什么不这样使用它(我不确定 .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!";
}

【讨论】:

  • 这也很完美,但我想了解为什么绑定的版本没有,以及如何正确地做到这一点。
【解决方案3】:

当通过 Itemsource 进行数据绑定时即使源被修改也不刷新this may solve refresh problem

【讨论】:

    猜你喜欢
    • 2011-09-29
    • 2019-07-13
    • 1970-01-01
    • 2018-04-13
    • 1970-01-01
    • 2012-06-24
    • 2012-12-27
    • 1970-01-01
    • 2021-04-06
    相关资源
    最近更新 更多