每次单击按钮时,我都尝试添加 1 来标记内容,但我需要在它自己的类中执行此操作(它必须是铁矿,当挖矿有自己的类时)。
public class Mining
{
public static int iron = 0;
public void mine_iron_Click(object sender, RoutedEventArgs e)
{
iron++;
label.Content = Convert.ToString(iron);
}
}
当我在挖掘类中使用此代码时,它给我一个错误,指出当前内容中不存在标签。如何使标签可从此类访问?我坚持我使用 MVVM,有什么想法如何在 MVVM 模式中实现这个简单的代码吗?
Mining mining =new mining(passlablelhere);
var lbl = "";
Public Mining(string labelfromview)
{
lbl =labelfromview;//here you can perform the logic
}
首先实现 INotifyPropertyChanged,然后将 Iron 属性绑定到 iron
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));
}
}
}
确保祖先的数据上下文正在挖掘,然后将标签添加到 xaml。
<Label Content="{Binding iron}" />