UWP 中的数据绑定不刷新
Data Binding in UWP doesn't refresh
我正在尝试将 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!";
}
为什么你在代码隐藏时不这样使用它(我不确定 .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!";
}
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");
}
Plus it is important to raise PropertyChanged in the setter of Text.
当通过 Itemssource 进行数据绑定时,即使源被修改也不刷新 this may solve refresh problem
我正在尝试将 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!";
}
为什么你在代码隐藏时不这样使用它(我不确定 .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!";
}
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");
}
Plus it is important to raise PropertyChanged in the setter of Text.
当通过 Itemssource 进行数据绑定时,即使源被修改也不刷新 this may solve refresh problem