MVVM pattern and nested view models - communication and lookup lists
- by LostInWPF
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 :-
Is this the best way to put lookup lists in a view which can be re-used across screens?
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?
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.