MVVM pattern and nested view models - communication and lookup lists

Posted by LostInWPF on Stack Overflow See other posts from Stack Overflow or by LostInWPF
Published on 2010-05-06T18:49:09Z Indexed on 2010/05/09 14:58 UTC
Read the original article Hit count: 1104

Filed under:
|
|
|
|

I am using Prism for a new application that I am creating. There are several lookup lists that will be used in several places in the application. Therefore it makes sense to define it once and use that everywhere I need that functionality. My current solution is to use typed data templates to render the controls inside a content control.

   <DataTemplate DataType={x:Type ListOfCountriesViewModel}>
       <ComboBox ItemsSource={Binding Countries} SelectedItem="{Binding SelectedCountry"/>      </DataTemplate>
   <DataTemplate DataType={x:Type ListOfRegionsViewModel}>
       <ComboBox ItemsSource={Binding Countries} SelectedItem={Binding SelectedRegion} />   </DataTemplate>

    public class ParentViewModel
   {
        SelectedCountry get; set;
        SelectedRegion get; set;
        ListOfCountriesViewModel CountriesVM;
        ListOfRegionsViewModel RgnsVM;
   }

Then in my window I have 2 content controls and the rest of the controls

<ContentControl Content="{Binding CountriesVM}"></ContentControl>
<ContentControl Content="{Binding RgnsVM}"></ContentControl>
<Rest of controls on view>

At the moment I have this working and the SelectedItems for the combo boxes are publising events via EventAggregator from the child view models which are then subscribed to in the parent view model.

I am not sure that this is the best way to go as I can imagine I would end up with a lot of events very quickly and it will become unwieldy. Also if I was to use the same view model on another window it will publish the event and this parent viewmodel is subscribed to it which could have unintended consequences.

My questions are :-

  1. Is this the best way to put lookup lists in a view which can be re-used across screens?
  2. How do I make it so that the combobox which is bound to the child viewmodel sets the relevant property on the parent viewmodel without using events / mediator. e.g in this case SelectedCountry for example?
  3. Any alternative implementation proposals for what I am trying to do?

I have a feeling I am missing something obvious and there is so much info it is hard to know what is right so any help would be most gratefully received.

© Stack Overflow or respective owner

Related posts about mvvm

Related posts about nested