我有一个TextBlock
( caloriesAvailableTextBlock
)我正在尝试更新。 Button
( eatCaloriesButton
) 应该减少 TextBlock
的数量绑定(bind)为 100。但是,TextBlock
不会更新。它仍然停留在 2000 年。我缺少什么想法吗?
HubPage.xaml 中的我的 xaml:
<StackPanel>
<TextBlock TextWrapping="Wrap" Text="Calories Available:" FontSize="24"/>
<TextBlock x:Name="caloriesAvailableTextBlock" Loaded="caloriesAvailableTextBlock_Loaded" TextWrapping="Wrap" Text="{Binding}" FontSize="36"/>
<Button x:Name="eatCaloriesButton" Content="Eat 100 Calories" HorizontalAlignment="Stretch" VerticalAlignment="Stretch" FontSize="18" Click="eatCaloriesButton_Click" FontFamily="Global User Interface"/>
</StackPanel>
我在 HubPage.xaml.cs 中的代码:
public CalorieTracker CalorieTracker { get; set; }
private void NavigationHelper_LoadState(object sender, LoadStateEventArgs e)
{
CalorieTracker = new CalorieTracker();
CalorieTracker.CaloriesAvailable = 2000;
}
private void eatCaloriesButton_Click(object sender, RoutedEventArgs e)
{
CalorieTracker.CaloriesAvailable -= 100;
}
private void caloriesAvailableTextBlock_Loaded(object sender, RoutedEventArgs e)
{
((TextBlock)sender).DataContext = CalorieTracker.CaloriesAvailable;
}
我的CalorieTracker.cs
保存我正在更新的号码的类:
public class CalorieTracker : INotifyPropertyChanged
{
private int caloriesAvailable;
public int CaloriesAvailable
{
get { return caloriesAvailable; }
set { caloriesAvailable = value;
NotifyPropertyChanged("CaloriesAvailable");
}
}
public event PropertyChangedEventHandler PropertyChanged;
private void NotifyPropertyChanged(String propertyName)
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
}
}
我的理解是,每当 CalorieTracker.CaloriesAvailable
发生变化,它会让该变量的所有出现都知道,但事实并非如此。知道为什么不吗?还是我离基地太远了?
最佳答案
这里的问题似乎是您如何设置绑定(bind)。
您将整个 DataContext 设置为文本 block 的该 int。这不是您想要做的。为了在变量更改时进行更新,很多东西都必须有所不同(对于初学者来说,运行时必须监听 DataContextChanged
而不是 PropertyChanged
)。
相反,将页面的 DataContext
设置为您的 View 模型,然后绑定(bind)到属性:
<TextBlock x:Name="caloriesAvailableTextBlock" TextWrapping="Wrap" Text="{Binding CaloriesAvailable}" FontSize="36"/>
private void NavigationHelper_LoadState(object sender, LoadStateEventArgs e)
{
DataContext = CalorieTracker = new CalorieTracker();
CalorieTracker.CaloriesAvailable = 2000;
}
现在,您的 NotifyPropertyChanged
将真正执行您所期望的操作,并且您的 UI 将更新。无论如何,这更适合 MVVM 模式。
关于c# - 文本 block 不会更新,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24900100/