¿Cómo anido múltiples ViewModels en un ViewModel de nivel superior, en una especie de jerarquía que se puede dispersar en todas mis Vistas?

Right now I have a rather large ViewModel llamado MainViewModel, that contains a lot of commands and properties that could be organized into more reasonably named ViewModels.

I however, only have one window, and so need to be able to cherry-pick the valid data and Commands from each of the SubViewModels....

I figure this could be achieved using properties, but I'm not so sure how to approach this in the XAML. (Or if there is an implication in the ViewModels themselves)

I realize that I can set the DataContext on SubViews as I see fit, but I want to avoid having my View dictate the hierarchy/organization of my ViewModels.

Ex. pseudo code

SubAViewModel mvmB = new SubBViewModel();
SubAViewModel mvmA = new SubAViewModel();
MainViewModel mvm = new MainViewModel( mvmA, mvmB );

<Window DataContext="{StaticResource MainViewModel}">

    //This is clearly wrong but is sort of what I am trying to achieve
    <MenuItem Command="{Binding Path=MainViewModel.SubAVM.TargetCmd}" />

Es muy posible que un MenuItem o alguna otra UserControl would want to access a Command in SubBViewModel and a property in SubAViewModel.

preguntado el 08 de enero de 11 a las 23:01

1 Respuestas

If you set the data context of the View to the MainViewModel and you expose the SubAVM as a property like this one:

public SubViewModel SubAVM { 
   get { 
      return subAVM;
   if (subAVM == value)
   subAVM = value; //implement the OnPropertyChanged ...

Of course the Path on a MenuItem would be SubAVM.TargetCmd as by the dependency hierarchy the main path is already MainViewModel for a Menu.

Respondido el 09 de enero de 11 a las 02:01

No es la respuesta que estás buscando? Examinar otras preguntas etiquetadas or haz tu propia pregunta.