Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can a View have two View Models as its Data Context?

Tags:

binding

wpf

xaml

I have two datagrids in a single view but the collections which are ItemsSource of these datagrids are in different View Models. So is it possible to bind these two datagrids with the collections in two different View Models?

like image 381
PhOeNiX Avatar asked May 28 '12 08:05

PhOeNiX


2 Answers

Go for a view model combining both:

public class ViewModelA {
    public ObservableCollection<CustomClass> Items { get; set; }
    /* properties, etc. */
}

public class ViewModelB {
    /* properties, etc. */
}

public class CombiningViewModel {
    public ViewModelA A { get; set; }
    public ViewModelB B { get; set; }
}

Binding can be done like

<DataGrid ItemsSource="{Binding A.Items}">
    <!-- Sample, not complete -->
</DataGrid>
like image 91
Sascha Avatar answered Oct 07 '22 00:10

Sascha


No, not directly. You do have options though:

You could set the DataCOntext of the view to itself, then expose each viewmodel through a separate property and bind to those properties:

public class MyView : Window 
{
    public MyView()
    {
        this.DataContext = this;
    }

    public ViewModel1 FirstViewModel { get; set; }

    public ViewModel2 SecondViewModel { get; set; }

}

Or you could make a wrapper viewmodel which either extends (inherits from) one of the viewmodels, or wraps them both and surfaces the appropriate properties:

public class MyCompositeViewModel
{
    public ViewModel1 FirstViewModel { get; set; }

    public ViewModel2 SecondViewModel { get; set; }
}
like image 43
slugster Avatar answered Oct 07 '22 01:10

slugster