2014-02-18 92 views
2

我是WPF的新手,並且在設置綁定到DataGrid時遇到問題。我的問題是,我不斷收到StackOverFlowException,並且調試器在FirstName屬性的設置語句中斷了。我已經提到了後續資源,是不能解決我的問題:DataGrid WPF StackOverFlow異常

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

有關與其他人誰具有相同的問題屬性設置遞歸信息,pleaase即時通訊pleasee看到:

Why would this simple code cause a stack overflow exception?

回答

2

FirstName = value;導致遞歸調用的財產二傳手。讓這樣的事情:

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

謝謝帕維爾!我只想添加此鏈接,以獲取有關具有相同問題的任何其他人的屬性設置遞歸的信息。 [遞歸屬性setter(http://stackoverflow.com/questions/7063827/why-would-this-simple-code-cause-a-stack-overflow-exception) – justanotherdev