Windows应用商店绑定问题

时间:2012-11-13 08:26:59

标签: xaml binding windows-8 windows-runtime

我有一个Windows Store项目如下:

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 个答案:

答案 0 :(得分:2)

您的班级似乎没有实施INotifyPropertyChanged。 我的意思是我希望看到class MyModel : INotifyPropertyChanged

答案 1 :(得分:1)

首先,视图模型必须实现INotifyPropertyChanged或更好地使用某种类型的MVVM库,如MVVM Light,这将对您有所帮助。
其次,我不确定,如果调用thisModel.TestVariable ++实际更新了值?尝试使用thisModel.TestVariable = thisModel.TestVariable + 1;

相关问题