我试图在每次点击按钮时为标签内容添加1,但我需要在它自己的类中进行(它必须是铁挖掘,当挖掘它拥有它自己的类时)。
public class Mining
{
public static int iron = 0;
public void mine_iron_Click(object sender, RoutedEventArgs e)
{
iron++;
label.Content = Convert.ToString(iron);
}
}
当我在Mining类中使用此代码时,它给出了一个错误,指出标签不存在于当前内容中。如何从此课程中获取标签?我认为我使用MVVM,任何想法如何在MVVM模式中实现这个简单的代码?
答案 0 :(得分:0)
Mining mining =new mining(passlablelhere);
var lbl = "";
Public Mining(string labelfromview)
{
lbl =labelfromview;//here you can perform the logic
}
答案 1 :(得分:0)
首先实现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));
}
}
}
确保祖先的datacontext正在挖掘,然后将标签添加到xaml。
<Label Content="{Binding iron}" />