我有一个TextBlock
(caloriesAvailableTextBlock
),我正在尝试更新。 Button
(eatCaloriesButton
)应该将TextBlock
绑定的数量减少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
发生变化时,它都会让所有出现的变量都知道,但这不是正在发生的事情。知道为什么不呢?还是我离基地不远?
答案 0 :(得分:2)
此处的问题似乎是您设置绑定的方式。
将整个DataContext 设置为文本块的int。这是不你想做什么。为了更新变量,很多东西必须是不同的(对于初学者来说,运行时必须在DataContextChanged
而不是PropertyChanged
上听。)
相反,将页面的DataContext
设置为视图模型,然后绑定到属性:
<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
实际上会按预期执行,您的用户界面会更新。无论如何,这更适合MVVM模式。