tags:

views:

133

answers:

3

Hi

My question is actually about starting an application with MVVM :

My main screen will host many screens. I understand that they will be UserControls.

But i don't see where i instantiate then when i want, when i show them and when i hide them ?

The logic is not clear to me. Can someone explain me or point me to a simple and clear example ?

Thanks John

A: 

Josh Smith's article in MSDN magazine is probably the best place to get started.

Pete OHanlon
I have studied this application and its article. Excellent. But still i did not manage to understand how i can change the user control to display when i click on a button ( a menu button for instance)
A: 

You could use an existing application framework to help manage this rather than doing it yourself. Caliburn in particular addresses this problem with its IPresenter Component Model. I'm sure there are others out there too.

GraemeF
A: 

Imagine that you have got a MainViewModel which binds to the main screen.Let the MainViewModel be a singleton class and it has a 'CurrentViewModel' property (INotifypropertyChanged implemented) in it. Now you can instantiate any particular ViewModel (based on a Command/Click) and assign the instance as below

MainViewModel.Instance.CurrentViewModel = new SomeViewModel();

So now your main screen XAML will have

  <Window> 
     <ContentControl Content="{Binding CurrentViewModel,Source={x:static vm:MainViewModel.Instance}}"
 </Window>

You need to define proper DataTemplates for each ViewModels (View to ViewModel Mapping). That will look like

<DataTemplate DataType="{x:Type vm:SomeViewModel}">
     <view:SomeView/>
</DataTemplate>

Here SomeView is the UserControl corresponds to the SomeVieModel.

Hope this explains the MVVM architecture very briefly

Jobi Joy
Excellent begining. Why should i need DataTemplate ?
Because that is the way WPF decides to which usercontrol your ViewModel class needs to instantiate. There will be many DataTemplate declaration in your Application. Mainly in the Resource file (or App.xaml)
Jobi Joy
This confuses me, because i thought that binding to a View would be enought. do you know of a full (simple) sample i can look at?
I got your point, as you saying binding to a View also might work, but then we cant say it is a pure MVVM.
Jobi Joy
because you "decouple again" ? what is the advantage to add another indirection via the DataTemplate?
It is not really an indirection. You are going to get a clean seperation between ViewModel and View. And the idea in MVVM is 'ViewModel' decide the 'View', But in a complex environment you can see Same Viewmodel shared to many userControls(You can use DatTemplate.DataTrigger for that)
Jobi Joy