I guess my problem has something to do with the databinding:
My.xaml adding viewmodel:
<Grid.Resources>
<vm:FreeTrainingViewModel x:Key="FreeTrainingViewModel"></vm:FreeTrainingViewModel>
</Grid.Resources>
My .xaml Textblock:
<TextBlock FontFamily="Segoe WP Black" FontSize="300" HorizontalAlignment="Center" VerticalAlignment="Center" Text="{Binding PushupsCount, Source={StaticResource FreeTrainingViewModel}}" ></TextBlock>
My Viewmodel:
public class FreeTrainingViewModel:INotifyPropertyChanged
{
private int _pushupsCount;
public int PushupsCount
{
get { return _pushupsCount; }
set { _pushupsCount = value; OnPropertyChanged("_pushupsCount"); Debug.WriteLine("Triggered PropertyChanged"); }
}
public event PropertyChangedEventHandler PropertyChanged;
private void OnPropertyChanged(string propertyName)
{
if (PropertyChanged != null)
PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
}
Code behind my view:
public sealed partial class FreeTraining : Page
{
FreeTrainingViewModel FreeTrainingViewModel = new FreeTrainingViewModel();
public FreeTraining()
{
this.InitializeComponent();
} //Method for adding +1 to the pushupsCount "FreeTrainingViewModel.PushupsCount+1;"
}
The PropertyChangedEvent is getting triggered, the property is changing fine, but the textblock isn't updating.
I don't know what is wrong. Help me to find the bug pls.
答案 0 :(得分:2)
There are 2 problems on your code:
You need to call the OnPropertyChanged with your property name ("PushupsCount") instead of your private member name ("_pushupsCount")
You create 2 instances of FreeTrainingViewModel:
In your .xaml file:
<Grid x:Name="gridName">
<Grid.Resources>
<vm:FreeTrainingViewModel x:Key="FreeTrainingViewModel"></vm:FreeTrainingViewModel>
</Grid.Resources>
</Grid>
In your code behind:
public sealed partial class FreeTraining : Page
{
FreeTrainingViewModel FreeTrainingViewModel;
public FreeTraining()
{
this.InitializeComponent();
FreeTrainingViewModel = (FreeTrainingViewModel)gridName.FindResource("FreeTrainingViewModel");
} //Method for adding +1 to the pushupsCount "FreeTrainingViewModel.PushupsCount+1;"
}