locked
Observable Collection and INotifyPropertyChange + NullReferenceException problem RRS feed

  • Question

  • hi, What's wrong with this code? An exception of type 'System.NullReferenceException' on "eventHandler(this, new PropertyChangedEventArgs(propertyname));" line.


    File City.cs

    namespace Banks.Classes
    {
        public class City : INotifyPropertyChanged
        {
            // name city
            private string _name = string.Empty;

            public string Name
            {
                get
                {
                    return this._name;
                }
                set
                {
                    if (this._name != value)
                    {
                        this._name = value;
                        OnPropertyChanged("Name");
                    }
                }
            }


            public event PropertyChangedEventHandler PropertyChanged;

            protected virtual void OnPropertyChanged(string propertyname)
            {
                var eventHandler = this.PropertyChanged;
                if (eventHandler == null)
                {
                    eventHandler(this, new PropertyChangedEventArgs(propertyname));
                }
            }
        }
    }



    File MainPage.xaml.cs

    namespace Banks
    {

        public sealed partial class MainPage : Page
        {

            public ObservableCollection<City> cities { get; set; }

            public MainPage()
            {
                this.InitializeComponent();

                this._loadCities();
            }

            private void _loadCities()
            {
                City city = new City();
                city.Name = "new york";
                cities.Add(city);
            }

        }

    }

    Friday, November 15, 2013 12:08 AM

Answers

  • You're calling eventhandler if it is equal to null. You want not-equal:
           if (eventHandler != null) // <== fix this
           {
                eventHandler(this, new PropertyChangedEventArgs(propertyname));
           }

    • Marked as answer by Fabio Guaraldo Friday, November 15, 2013 11:53 AM
    Friday, November 15, 2013 12:36 AM
    Moderator