none
Composite ViewModels in WPF RRS feed

  • Question

  • Is it possible to have view model composed of other view models? How would this work in practice? I have data that is reused in several views and I have views that are made up several groups of data. So essentially I would like a many to many relationship between views and view models and my limited understanding is that it is a many to one relationshop between views and view models.

    Thursday, August 12, 2010 12:06 AM

All replies

  • you can you a VM for all your views in the templet you mention the relation between which view is assosiated to which VM there you can set up 5 views to 1 VM

     

     <DataTemplate DataType="{x:Type vm:SelectListViewModel}">

            <vw:SelectListView />

        </DataTemplate>

    Monday, August 23, 2010 4:20 PM
  • Yes, you can definitely have a composition of view models.  Basically, treat the child view model as any other property you'd have on a view model.  As an example:

    public class ClientViewModel
    {
     public AddressViewModel CompanyAddress { get; set; }
    
     public PersonViewModel ContactPerson { get; set; }
    
     public ContactInfoViewModel ContactInformation { get; set; }
    }
    

    In your view, you could either do what Reddy MCAD suggests, or create a similar view composition:

    <UserControl ...>
     <StackPanel>
      <views:PersonView DataContext="{Binding ContactPerson}"/>
      <views:ContactInfoView DataContext="{Binding ContactInformation}"/>
      <views:AddressView DataContext="{Binding CompanyAddress}"/>
     </StackPanel>
    </UserControl>
    
    

    • Proposed as answer by TI82 Monday, August 23, 2010 4:47 PM
    Monday, August 23, 2010 4:47 PM