DataGrid WPF StackOverFlow异常

时间:2014-02-18 05:44:52

标签: c# wpf binding datagrid

我是WPF的新手,在设置与DataGrid的绑定时遇到问题。我的问题是我不断获得StackOverFlowException并且调试器在FirstName属性的set语句中断开。我已经提到了以下资源,无法解决我的问题:

msdn databinding overview
stackoverflow-with-wpf-calendar-when-using-displaydatestart-binding
how-to-get-rid-of-stackoverflow-exception-in-datacontext-initializecomponent

非常感谢任何帮助。

我的代码是:

namespace BindingTest
{
  public partial class MainWindow : Window
  {
    public MainWindow()
    {
      InitializeComponent();

      ObservableCollection<Person> persons = new ObservableCollection<Person>()
      {
         new Person(){FirstName="john", LastName="smith"},
         new Person(){FirstName="foo", LastName="bar"}
      };

      dataGrid1.ItemsSource = persons;
    }

    class Person : INotifyPropertyChanged
    {
      public string FirstName
      {
        get
        {
          return FirstName;
        }

        set
        {
          FirstName = value;
          NotifyPropertyChanged("FirstName");
        }
      }

      public string LastName
      {
        get
        {
          return LastName;
        }

        set
        {
          LastName = value;
          NotifyPropertyChanged("LastName");
        }
      }

      public event PropertyChangedEventHandler PropertyChanged;

      private void NotifyPropertyChanged(String propertyName)
      {
        var handler = PropertyChanged;
        if (handler != null)
        {
          handler(this, new PropertyChangedEventArgs(propertyName));
        }
      }
    }
  }
}

Note about answer

有关具有相同问题的任何其他人的属性设置递归的信息,请看:

Why would this simple code cause a stack overflow exception?

1 个答案:

答案 0 :(得分:2)

FirstName = value;导致属性setter的递归调用。做这样的事情:

private string firstName;
public string FirstName
{
    get { return firstName;}
    set
    {
        this.firstName = value;
        /*...*/
    }
}