2012-11-13 80 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 –