问题
I have a TextBlock
(caloriesAvailableTextBlock
) which I am trying to update. The Button
(eatCaloriesButton
) is supposed to reduce the number which the TextBlock
is bound to by 100. However, the TextBlock
will not update. It just remains at 2000. Any ideas what I am missing?
My xaml in HubPage.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>
My code behind in 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;
}
My CalorieTracker.cs
class which holds the number which I am updating:
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));
}
}
}
My understanding is that whenever CalorieTracker.CaloriesAvailable
is changed, it will let all occurences of that variable know, but that is not what is happening. Any idea why not? Or am I just way off base?
回答1:
The problem here appears to be how you set up your binding.
You set the whole DataContext to that int for your textblock. This is not what you want to do. For that to update on variable change, well, a lot of stuff would have to be different (for starters the runtime would have to listen on DataContextChanged
instead of PropertyChanged
).
Instead, set the DataContext
for the page to your view model, then bind to a property:
<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;
}
Now your NotifyPropertyChanged
will actually do what you expected, and your UI will update. This is a much better fit for the MVVM pattern anyways.
来源:https://stackoverflow.com/questions/24900100/textblock-wont-update