2017-09-06 33 views
1

我有這樣的視圖模型:如何讓我的視圖顯示0,當後面的屬性的值是0開始?

public class PhrasesFrameViewModel : ObservableProperty 
{ 
    int points1; 

    public int Points1 
    { 
     get { return points1; } 
     set 
     { 
      if (value != points1) 
      { 
       points1 = value; 
       NotifyPropertyChanged("Points1"); 
      } 
     } 
    } 

應用程序啓動時points1的值設置爲0瀏覽:

card.Points1 = App.correctAnswerPerPhrase; // returns a 0 

當我看着我的屏幕上我什麼也看不見,然後調試我看到它的因爲setter正在檢查值(0)是否不等於points1(0)的默認值;

那麼我怎樣才能讓它在屏幕上0出現在開始時的值爲0?

回答

3

從技術上講,你的代碼仍然可以工作;因爲在裝載期間,檢索的值將僅爲0。但是,如果你仍然希望能夠通過設定值通知,您可以使用可爲空的int作爲類型。

int? points1 = null; 

public int? Points1 
{ 
    get { return points1; } 
    set 
    { 
     if (value != points1) 
     { 
      points1 = value; 
      NotifyPropertyChanged("Points1"); 
     } 
    } 
} 

EDIT 1

如果屬性上目標控制類型是字符串(例如EntryText。);那麼你將需要將值轉換爲字符串。你可以通過創建一個converter或者一個包裝屬性來實現。

int points1; 

public int Points1 
{ 
    get { return points1; } 
    set 
    { 
     if (value != points1) 
     { 
      points1 = value; 
      NotifyPropertyChanged("Points1"); 
      NotifyPropertyChanged("Points1Str"); 
     } 
    } 
} 

// bind this property to control 
public string Points1Str 
{ 
    get { return points1.ToString(); } 
    set { 
     int parsedValue = 0; 
     if (int.TryParse(value, out parsedValue)) 
      points1 = parsedValue; 
    } 
} 
+0

謝謝。目標是一個標籤,所以我仍然需要轉換爲字符串? – Alan2

+1

不要這樣想。使用標籤(或可模式爲OneWay的可綁定屬性)不應該需要轉換器。 – Ada

相關問題