SubViewModels

Oct 24, 2010 at 2:45 PM

Hi

I have been reading over the different documents and links and somewhere I noticed something about subviewmodels, are there any examples that show this feature ?

 

Thanks

Coordinator
Oct 25, 2010 at 7:39 PM
Edited Oct 25, 2010 at 7:40 PM

Hi terryh,

Thanks for your feedback. The idea of Sub-ViewModels is to separate the responsibilities of a ViewModel into more classes. One class represents the main ViewModel and the other classes are the sub ViewModels.

Remark: If a ViewModel gets too large for a single class then reconsider the application design first before you start creating Sub-ViewModels.

Example that uses a Sub-ViewModel:

The PersonViewModel is the main ViewModel and the AddressViewModel is the sub ViewModel. Both ViewModel objects are consumed by the same PersonView. The only difference in the ViewModel implementation is that the Sub-ViewModel calls the constructor of the base class with the value true for the “isChild” parameter.

[Export]
internal class PersonViewModel : ViewModel<IPersonView>
{
    private readonly AddressViewModel addressViewModel;

    [ImportingConstructor]
    public PersonViewModel(IPersonView view) : base(view)
    {
        addressViewModel = new AddressViewModel(view);
    }

    public AddressViewModel AddressViewModel { get { return addressViewModel; } }

    ...
}
internal class AddressViewModel : ViewModel<IPersonView>
{
    public AddressViewModel(IPersonView view) : base(view, true)
    {
    }

    public string Street { get; set; }
}
Extract from PersonView.xaml:

<TextBox Text="{Binding Path=AddressViewModel.Street}"/>