UWP 中的数据绑定不会刷新
本文关键字:刷新 数据绑定 UWP | 更新日期: 2023-09-27 18:35:06
我正在尝试将 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!";
}
x:Bind
的默认绑定模式是OneTime
,而不是OneWay
事实上是Binding
的默认值。此外,text
private
。要有一个工作绑定,你需要有一个public property
。
<TextBlock Text="{x:Bind Text , Mode=OneWay}" />
在代码隐藏中
private string _text;
public string Text
{
get { return _text; }
set
{
_text = value;
NotifyPropertyChanged("Text");
}
另外,在 Text 的设置器中提高 PropertyChanged 很重要。
无论如何,
当你在代码后面时,为什么你不这样使用它(我不确定.文字也许是.内容只是尝试一下):
<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 的数据绑定不刷新时,即使修改了源代码,这可能会解决刷新问题