WPF绑定不起作用

时间:2013-06-10 05:41:33

标签: c# wpf mvvm binding

我是WPF的新手。我使用MVVM开发了此测试WPF应用程序。但绑定不起作用。但据我所知,没有错误可以检测到。任何人都可以帮忙。下面的图像和编码显示测试应用程序。

enter image description here

enter image description here

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));
        }
    }
}
}

3 个答案:

答案 0 :(得分:2)

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

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

没用。你必须设置this.DataContext = this;在你的MainWindow ctor。顺便说一下为什么你需要一个静态的学生对象?

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

使用此代码,您的datacontext是您的主窗口,现在您的绑定可以正常工作。

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

答案 1 :(得分:1)

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

this.DataContext=sc;

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

答案 2 :(得分:0)

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

this.DataContext=new Student();

Add the default constructor in Student.cs
public Student()
{
}
相关问题