[英]Textblock ui not updating Mvvm c#
I guess my problem has something to do with the databinding: 我想我的问题与数据绑定有关:
My.xaml adding viewmodel: My.xaml添加viewmodel:
<Grid.Resources>
<vm:FreeTrainingViewModel x:Key="FreeTrainingViewModel"></vm:FreeTrainingViewModel>
</Grid.Resources>
My .xaml Textblock: 我的.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. PropertyChangedEvent被触发,属性改变得很好,但是文本块没有更新。
I don't know what is wrong. 我不知道怎么了 Help me to find the bug pls. 帮我找到错误请。
There are 2 problems on your code: 您的代码有2个问题:
You need to call the OnPropertyChanged with your property name ("PushupsCount") instead of your private member name ("_pushupsCount") 您需要使用属性名称(“ PushupsCount”)而不是私有成员名称(“ _pushupsCount”)来调用OnPropertyChanged
You create 2 instances of FreeTrainingViewModel: 您创建2个FreeTrainingViewModel实例:
In your .xaml file: 在您的.xaml文件中:
<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;"
} }
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.