2012-11-13 81 views
0

我有一個Windows應用商店項目如下:Windows應用商店綁定問題

class MyModel 
{ 
    private int _testVar; 
    public int TestVariable 
    { 
     get { return _testVar; } 
     set 
     { 
      _testVar = value; 
      NotifyPropertyChanged("TestVariable"); 
     } 
    } 

    public event PropertyChangedEventHandler PropertyChanged; 

    private void NotifyPropertyChanged(string property) 
    { 
     if (PropertyChanged != null) 
      PropertyChanged(this, new PropertyChangedEventArgs(property)); 
    } 


} 

我結合如下:

<Grid Background="{StaticResource ApplicationPageBackgroundThemeBrush}"> 
    <TextBlock Text="{Binding Path=TestVariable}" /> 
    <Button Click="Button_Click_1"></Button> 
</Grid> 

而後面的代碼:

MyModel thisModel = new MyModel(); 

    public MainPage() 
    { 
     this.InitializeComponent(); 

     thisModel.TestVariable = 0; 
     DataContext = thisModel; 
    } 

由於這點,綁定似乎工作,因爲我得到的文本塊顯示爲0.但是,當我處理按鈕單擊事件如下:

private void Button_Click_1(object sender, RoutedEventArgs e) 
    { 
     thisModel.TestVariable++; 
    } 

我沒有看到數字增加。我在這裏錯過了什麼?

回答

2

看來你的班級沒有執行INotifyPropertyChanged。 我的意思是我希望看到class MyModel : INotifyPropertyChanged

+0

不能相信我錯過了! –

1

首先,視圖模型必須執行INotifyPropertyChanged或更好的使用某種MVVM圖書館像MVVM Light,這將幫助你很多。
其次,我不確定,如果調用thisModel.TestVariable ++實際更新值?嘗試使用thisModel.TestVariable = thisModel.TestVariable + 1;

+0

毫無疑問,++會提高PropertyChanged。 – Nagg

+0

我可以確認thisModel.TestVariable ++確實工作正常,一旦我實現INotifyPropertyChnaged –