C# 每次使用MVVM单击按钮时添加int
我试图在每次单击按钮时向标签内容添加1,但我需要在它自己的类中进行添加(必须是iron mining,当mining有自己的类时)C# 每次使用MVVM单击按钮时添加int,c#,wpf,mvvm,data-binding,C#,Wpf,Mvvm,Data Binding,我试图在每次单击按钮时向标签内容添加1,但我需要在它自己的类中进行添加(必须是iron mining,当mining有自己的类时) 当我在挖掘类中使用此代码时,它会给我一个错误,告诉我当前内容中不存在标签。如何使标签可从此类访问?我想我使用的是MVVM,有没有想法如何在MVVM模式中实现这个简单的代码?首先实现INotifyPropertyChanged,然后将Iron属性绑定到Iron Mining mining =new mining(passlablelhere); var lbl =
当我在挖掘类中使用此代码时,它会给我一个错误,告诉我当前内容中不存在标签。如何使标签可从此类访问?我想我使用的是MVVM,有没有想法如何在MVVM模式中实现这个简单的代码?首先实现INotifyPropertyChanged,然后将Iron属性绑定到Iron
Mining mining =new mining(passlablelhere);
var lbl = "";
Public Mining(string labelfromview)
{
lbl =labelfromview;//here you can perform the logic
}
public class Mining : INotifyPropertyChanged
{
public static int _iron
public int iron
{
get { return _iron; }
set
{
_iron = value;
OnPropertyChanged("iron");
}
}
public void mine_iron_Click(object sender, RoutedEventArgs e)
{
iron++;
}
protected void OnPropertyChanged(string Name)
{
PropertyChangedEventHandler handler = PropertyChanged;
if (handler != null)
{
handler(this, new PropertyChangedEventArgs(Name));
}
}
}
确保祖先的datacontext正在挖掘,然后将标签添加到xaml中
<Label Content="{Binding iron}" />
如果不从类访问标签,则将标签的内容
绑定到引发更改通知的视图模型属性。这是非常基本的MVVM,所以我建议找一些教程或类似的。这听起来像是大学作业。看起来您正试图直接更改UI,这在MVVM中是不应该做的。基于这段小代码,您似乎对如何创建ViewModel属性并在UI中绑定它们有了更大的误解,但这在一个如此复杂的问题中很难解决。我建议你通读一遍以确保你理解这些概念。改变标签内容没有多大用处,也不是MVVM。
<Label Content="{Binding iron}" />