0

我是新手WPF。我已经MVVM使用WPF. 但是绑定不起作用。但据我所知,没有发现任何错误。任何人都可以帮助解决这个问题。下面的图像和编码显示了测试应用程序。

在此处输入图像描述

在此处输入图像描述

Student.cs

using System;<br/>
using System.Collections.Generic;<br/>
using System.Linq;<br/>
using System.Text;
using System.ComponentModel;

namespace WpfNotifier
{
    public class Student : INotifyPropertyChanged
    {

    private string _name;
    public string Name
    {
        get { return this._name; }
        set
        {

            this._name = value;
            this.OnPropertyChanged("Name");
        }
    }
    private string _company;
    public string Company
    {
        get { return this._company; }
        set
        {
            this._company = value;
            this.OnPropertyChanged("Company");
        }
    }
    private string _designation;
    public string Designation
    {
        get { return this._designation; }
        set
        {
            this._designation = value;
            this.OnPropertyChanged("Designation");
        }
    }
    private Single _monthlypay;
    public Single MonthlyPay
    {
        get { return this._monthlypay; }
        set
        {
            this._monthlypay = value;
            this.OnPropertyChanged("MonthlyPay");
            this.OnPropertyChanged("AnnualPay");
        }
    }
    public Single AnnualPay
    {
        get { return 12 * this.MonthlyPay; }
    }


    public event PropertyChangedEventHandler PropertyChanged;

    private void OnPropertyChanged(string propertyName)
    {
        var handler = PropertyChanged;

        if (handler != null)
        {
            handler(this, new PropertyChangedEventArgs(propertyName));
        }
    }
}
}
4

3 回答 3

2

绑定只适用于公共属性,所以你的

 <Grid DataContext="{Binding Path=st}"> 

不工作。你必须设置 this.DataContext = this; 在您的 MainWindow ctor 中。顺便说一句,你为什么需要一个静态的学生对象?

  public MainWindow()
  {
     ...
     this.DataContext = this;
  }

使用此代码,您的数据上下文是您的主窗口,现在您的绑定可以工作。

要在运行时检查 DataContext 和 Bindings,您可以使用Snoop

于 2013-06-10T06:49:05.137 回答
1

尝试将Student实例附加sc到窗口DataContext。在MainWindow构造函数中添加以下行:

this.DataContext=sc;

许多 mvvm 库可以自动执行此操作。如果没有这些,您可以定义一个 Student 类型的嵌入式资源并将其设置为窗口的 DataContext。但作为一个建议,如果你想从 MWWM 开始,尝试一些已经制作的 OSS 库。

于 2013-06-10T05:49:54.227 回答
0

InitailizeComponent();语句后面的代码隐藏(xaml.cs)文件中添加以下代码:

this.DataContext=new Student();

Add the default constructor in Student.cs
public Student()
{
}
于 2013-06-10T06:16:34.610 回答