Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

INotifyPropertyChanged PropertyChangedEventHandler event is always null

I have implemented INotifyPropertyChanged to the following class

 public class FactoryItems : INotifyPropertyChanged
    {
        public event PropertyChangedEventHandler PropertyChanged;

        string symbol;
        public string Symbol
        {
            get { return symbol; }
            set { symbol = value; OnPropertyChanged("Symbol"); }
        }

        public FactoryItems()
        {

        }

        protected void OnPropertyChanged(string name)
        {
            PropertyChangedEventHandler handler = PropertyChanged;
            if (handler != null)
            {
                handler(this, new PropertyChangedEventArgs(name));
            }
        }
    }

When the Symbol property changes the event fires with no problems but the PropertyChanged event is always null, this class gets instantiated once only, I placed a breakpoint on the constructor to make sure its the case.

In another class this is how I subscribe to it:

Data.Tables.FactoryItems = new Data.FactoryItems();
Data.Tables.FactoryItems.PropertyChanged += 
new System.ComponentModel.PropertyChangedEventHandler(FactoryItems_SymbolChanged);

void FactoryItems_SymbolChanged(object sender, System.ComponentModel.PropertyChangedEventArgs e)
{
  doSomething();
}

But the handler is always null as PropertyChanged is null. Any idea how to get this working?

Many thanks.

like image 369
Maya Avatar asked Feb 20 '11 16:02

Maya


2 Answers

Until someone subscribes to the event, it will remain null.

like image 172
SLaks Avatar answered Nov 06 '22 14:11

SLaks


There are various types that will subscribe to this - most notably thing like DataGridView (winforms, but similar in WPF etc) but only when data-bound (set DataSource), and only if the list also supports binding - for example BindingList<T>.

To test, simply subscribe to if yourself with PropertyChanged += ....

like image 1
Marc Gravell Avatar answered Nov 06 '22 14:11

Marc Gravell