Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

WPF + MvvM + Prism

I am new in the Wpf & Mvvm world , but I have found a couple of examples and just found that there is some different way to instantiate the model. I would like to know the best/correct way to do it. both ways are using Unity

What I've foud:

var navigatorView = new MainView();
navigatorView.DataContext = m_Container.Resolve<INavigatorViewModel>();
m_RegionManager.Regions["NavigatorRegion"].Add(navigatorView);

What I did:

var navigatorView = m_Container.Resolve<MainView>;
m_RegionManager.Regions["NavigatorRegion"].Add(navigatorView);

and I changed the constructor to receive viewmodel so I can point the datacontext to it:

public MainView(NavigatorViewModel navigatorViewModel)
{
 this.DataContext = navigatorViewModel;
}  

Other examples I've found another way like:

...vm = new viewmodel 
...m = new model
v.model = vm;

get/set DataContext

cheers

like image 256
2Fast4YouBR Avatar asked Feb 28 '23 02:02

2Fast4YouBR


1 Answers

I like Igor's suggestion, but without the viewmodel having knowledge of the view. I prefer my dependencies to go one direction (View -> ViewModel -> Model).

What I do is ViewModel-First and just DataTemplate the viewmodel. So I do this:

MainViewModel mainViewModel = container.Resolve<MainViewModel>();

region.Add(mainViewModel, "MainView");
region.Activate(mainViewModel);

With the addition of the ViewModel -> View mapping done with a WPF datatemplate (I don't think this approach is possible with Silverlight, though)

App.xaml:

<Application.Resources>
     <DataTemplate DataType="{x:Type viewModels:MainViewModel}">
          <views:MainView />
     </DataTemplate>
</Application.Resources>

That's it! I love this approach. I like the way it feels like magic. It also has the following advantages:

  • Don't have to modify constructors to suit the mapping
  • Don't have to register type for IMyViewModel in the container... you can work with concrete types. I like to keep my registrations to application services like IViewRegistry or ILogger... those kinds of things
  • You can change the mapping using resources scoped to a particular view that a region is in (this is nice if you want to reuse your ViewModels but want them to look different in different areas of the application
like image 193
Anderson Imes Avatar answered Mar 08 '23 09:03

Anderson Imes