B
B
bagos2015-03-26 17:05:38
WPF
bagos, 2015-03-26 17:05:38

How to force ListBox to update with INotifyPropertyChanged?

class MyClassA
{
        private ObservableCollection<AnotherClass> _listCode;
        public ObservableCollection<AnotherClass> ListCode
        {
            get
            {
                return _listCode;
            }
            set
            {
                if (value == _listCode) return;
                _listCode= value;
                OnPropertyChanged("ListCode");
            }
        }

     public void GetList()
     {
           ListCode = ...
     }

        public event PropertyChangedEventHandler PropertyChanged;

        protected virtual void OnPropertyChanged(string propertyName)
        {
            var handler = PropertyChanged;
            if (handler != null) 
                handler(this, new PropertyChangedEventArgs(propertyName));
        }
}

In XAML:
<ListBox ItemsSource="{Binding Path=ListCode}" ItemTemplateSelector="{StaticResource ListTemplateSelector}" />

In a paged class, it is associated with MyClass via the DataContext.
When GetList is executed in the class constructor, the ListBox displays the values, in the case when I call GetList after I updated the ListCode , the ListBox is not updated, although in the debugger I see that the ListCode contains a new element.
OnPropertyChanged doesn't work, why?
UPD And if you add an element to the ListCode and call GetList , then in this case the new element will be displayed in the ListBox. Doesn't work if GetList is called from another class...

Answer the question

In order to leave comments, you need to log in

1 answer(s)
V
vitvov, 2015-03-26
@bagos

Option 1: Your class must inherit INotifyPropertyChanged, only then it will work.
Option 2: ObservableCollection implements INotifyPropertyChanged itself, so to use it your code should look something like this:

class MyClassA
{
      public ObservableCollection<AnotherClass> ListCode { get; private set; };
        
      public MyClassA()
      {
            // ...
            ListCode = new ObservableCollection<AnotherClass>();
      }

      public void GetList()
      {
            ListCode.Clear();
            // ...
            ListCode.Add(new AnotherClass());
      }
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question