Reputation: 112
I am new to WPF and am having a problem with setting up binding to a DataGrid
. My issue is that I keep getting a StackOverFlowException
and the debugger breaks on the set statement of the FirstName
property. I have referred to the follow resources and was unable to solve my problem:
msdn databinding overview
stackoverflow-with-wpf-calendar-when-using-displaydatestart-binding
how-to-get-rid-of-stackoverflow-exception-in-datacontext-initializecomponent
Any help is greatly appreciated.
My code is:
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
For information about the recursion with property settings for anyone else who has the same issue, pleasee see this:
Why would this simple code cause a stack overflow exception?
Upvotes: 2
Views: 493
Reputation: 2791
FirstName = value;
causes recursive call of the property setter. Make something like this:
private string firstName;
public string FirstName
{
get { return firstName;}
set
{
this.firstName = value;
/*...*/
}
}
Upvotes: 2