Textblock ui not updating Mvvm c#

时间:2016-04-04 17:33:31

标签: c# xaml mvvm

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.

1 个答案:

答案 0 :(得分:2)

There are 2 problems on your code:

  1. You need to call the OnPropertyChanged with your property name ("PushupsCount") instead of your private member name ("_pushupsCount")

  2. You create 2 instances of FreeTrainingViewModel:

    • One in the Grid resources. This one is binding with the TextBlock
    • One in FreeTraining. You are trying to update this. You need to use the same instance at 2 places.

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;"

}