2

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?

1 Answer 1

2

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;
        /*...*/
    }
}
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you Pavel! I just wanted to add this link for information about the recursion with property settings for anyone else who has the same issue. recursive property setters

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.