我有一个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被更改时,它都会让所有发生的变量知道,但这不是正在发生的事情。知道为什么不行吗?还是我离基地很远?
发布于 2014-07-23 00:48:24
这里的问题似乎是如何设置绑定。
您可以为文本块将整个 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实际上将做您期望的事情,并且您的UI将更新。无论如何,这是一个更适合MVVM模式的方法。
https://stackoverflow.com/questions/24900100
复制相似问题