views:

37

answers:

3

I have the following two classes:

(1) IViewModelManager (2) WorkspaceViewModel

IViewModelManager has an ObservableCollection.

IViewModelManager is injected into WorkspaceViewModel's constructor.

I have a View that binds to WorkspaceViewModel - and in the view is a ListBox that needs to bind to a collection in WorkspaceViewModel. If I define a readonly property in WorkspaceViewModel that returns the ObservableCollection in IViewModelManager - will changes to the ObservableCollection always bubble up to the UI? For example, if I have another class called ViewModelManager that derives from IViewModelManager - and I perform some function in ViewModelManager that adds an item to the ObservableCollection, will the ListBox in the View that binds to the WorkspaceViewModel class pick up that change? If not, any idea on how to implement this using the architecture I've described?

Chris

+2  A: 

Yes, the changes will be sent to the UI. The ListBox binds to the ObservableCollection instance directly; it only uses the binding's property path to determine how to get there.

Bryan Watts
A: 

On the View Side :

Set ItemsSource of the Listbox to a bindable property like this :

ItemsSource="{Binding Path=BindingName, Mode=OneWay}"

On the View Model Side :

Declare a propery like this :

  private ObservableCollection<T> _BindingName = new ObservableCollection<T>();
    public ObservableCollection<T> BindingName {
        get { return _BindingName; }
        set {
            _BindingName = value;
            NotifyPropertyChanged("BindingName");
        }
    }

Everytime you change this property, you need to raise a propertyChanged Event to make the binding reflect the changes in the UI.

Matthieu
A: 

Yes, with a caveat. If your IViewModelManager instance swaps out the ObservableCollection, your View won't notice. For example:

public class VMMgr : IViewModelManager
{
    private ObservableCollection _oc;

    public ObservableCollection Collection { get { return _oc; } }

    // other implementation

    public void DoNaughtyThings()
    {
        _oc = new ObservableCollection();
    }
}

If someone comes and modifies _oc to point to a different instance of ObservableCollection (e.g. calls DoNaughtyThings()), your view won't notice that it changed.

My convention on this has been to have ViewModels inherit from DependencyObject and expose anything that the View binds to as DependencyProperties. YMMV, HTH.

FMM