WPF ObservableCollection and Listbox.itemsource exception

486 Views Asked by At

Editing this entire post to clarify... I cannot seem to nail this:

BackgroundWorker receives data from a WCF service that is a list of objects. The service reference is configured to be ObservableCollection.

I pass the ObservableCollection via a delegate into my main UI thread and set it equal to the UI threads Local Collection.

A listbox is bound to this local collection and does not update. I've added the following to my collection:

public ObservableCollection<EmployeeData> _empData { get; set; }

public event PropertyChangedEventHandler PropertyChanged;

public ObservableCollection<EmployeeData> EmpData
    {
        get { return _empData ; }
        set
        {
            _empData = value;
            OnPropertyChanged("EmpData");
        }
    }

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

This even fires but the PropertyChanged is always null. My XAML listbox has a binding declared as:

ItemsSource="{Binding Path=EmpData}"

No matter what I do EmpData updates but the ListBox does not, I've tried several other methods but nothing ever changes in the listbox, its always just null.

I've been working on this for over a day now, I cannot seem to get this whole automatic updating thing to 'click'.

1

There are 1 best solutions below

3
On

I'm not sure that I understand exactly what you are doing, but here are a couple of suggestions.

  • Have a single ObservableCollection
  • Bind your itemcollection (or listbox, or whatever) to this
  • Depending on the user, clear and fill that observablecollection with list data
  • Have the background worker update the list and refresh the observable collection if anything has changed.

Ideally your EmployeeData class will implement the INotifyPropertyChanged interface, so that property changes will get automatically updated in your view.