2016-06-10 57 views
-1

我試圖在每次單擊按鈕時添加1以標記內容,但是我需要在它自己的類中進行操作(它必須是鐵礦開採,當採礦擁有它時類)。每次使用MVVM點擊按鈕時添加int

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模式中實現這個簡單的代碼?

+5

您不會從類中訪問標籤,您*將標籤的「內容」綁定到視圖模型*屬性*,引發更改通知。這是非常基本的MVVM,所以我建議找一些教程或類似的東西。 –

+1

這聽起來像是一個大學作業。它看起來像你試圖直接改變UI,你不應該在MVVM中做。基於這一小段代碼,看起來你對如何創建ViewModel屬性有更大的誤解,並將它們綁定到UI中,但這很難在SO問題中解決。我建議通過https://msdn.microsoft.com/en-us/magazine/dd419663.aspx閱讀,以確保您瞭解這些概念。 –

回答

0
Mining mining =new mining(passlablelhere); 

var lbl = ""; 
Public Mining(string labelfromview) 
{ 
    lbl =labelfromview;//here you can perform the logic 
} 
+0

改變標籤內容沒有多大用處,它也不是MVVM。 –

0

首先執行INotifyPropertyChanged然後將鐵屬性綁定到鐵

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}" /> 
相關問題