Search code examples
c#wpfunity-containerprismprism-5

ObservableCollection loses its collection


Using WPF with Prism and Unity -

I have a strange defect where an ObservableCollection is losing its collection.

I’ve added a real backing field to see if there was something funny happening with the automatic property.

I’ve added a CollectionChanged event handler on the field that only fires when I’m expecting it.

I’m using service locator to retrieve the instance so I thought maybe I was getting a different instance, but the other properties and fields have the expected values from a previous access.

Storing the ViewModel -

this.Container.RegisterInstance(
new ShellViewModel(), new ContainerControlledLifetimeManager());  

Retrieving it -

return App.getUnityContainer().Resolve<ShellViewModel>();    

The ObservableCollection Field -

private readonly ObservableCollection<BusinessProcessViewModel> openBusinessProcesses =  
new ObservableCollection<BusinessProcessViewModel>();

ObservableCollection Property -

public ObservableCollection<BusinessProcessViewModel> OpenBusinessProcesses  
 { get { return openBusinessProcesses; } }

ObservableCollection Field Event Handler -

    private void AttachEventHandlers()
    {
        openBusinessProcesses.CollectionChanged += openBusinessProcesses_CollectionChanged;
    }

    void openBusinessProcesses_CollectionChanged(object sender, System.Collections.Specialized.NotifyCollectionChangedEventArgs e)
    {
        logger.Info(String.Format("OpenBusinessProcess collection changed. Action: {0}, Added: {1}, Removed: {2}", e.Action, e.NewItems, e.OldItems));
    }

Solution

  • Thanks Aleksey. You got me on the right track.

    I forgot I had added auto-wiring in the view, so I had two instances of the view model.

    This is the part I removed from the xaml markup -

    viewModel:ViewModelLocator.AutoWireViewModel="True"   
    

    Update for clarity -
    The ObservableCollection was NOT being emptied. The autowiring in the view, plus the explicit model creation resulted in two instances of the view model.