Ray
Ray

Reputation: 4947

wpf and prism: where is link between view and viewmodel

I've inherited a WPF Prism application and I'm having a tough time seeing how viewmodels are linked to their respective views (xaml). Sometimes the view's code behind sets the DataContext to the proper viewmodel but the application I'm working on does not have this being set in the code behind. Where else can this be set in a Prism application?

Upvotes: 0

Views: 2864

Answers (2)

Johnathon Sullinger
Johnathon Sullinger

Reputation: 7414

With Prism, View Models are auto-setup for you. There is typically a AutoWireViewModel=True property set in the View. The rest is done by convention. Prism looks for any ViewModels that match a specific naming convention. The default naming convention is YouPage for the view and YouPageViewModel for the view model.

View Models convention can be changed in the bootstrapper, which is usually the app.xaml.cs file. Using a ViewModelLocator, you can customize the naming convention. Most people just leave it as the default.

If it was setup properly, any constructor parameters required by the view models will be handed to them automatically as well using some form of an IoC container. Something like Autofac, Unity or Ninject. That too would be configured in the bootstrapper.

Upvotes: 2

Yuliam Chandra
Yuliam Chandra

Reputation: 14640

It can be setup from Xaml, Behind Code or View Model Locator.

Creating the View Model Using XAML

Perhaps the simplest approach is for the view to declaratively instantiate its corresponding view model in XAML. When the view is constructed, the corresponding view model object will also be constructed. You can also specify in XAML that the view model be set as the view's data context.

Creating the View Model Programmatically

Another approach is for the view to instantiate its corresponding view model instance programmatically in its constructor. It can then set it as its data context, as shown in the following code example.

Creating the View Model Using a View Model Locator

Another way to create a view model instance and associate it with its view is by using a view model locator.

Here is the documentation.

Upvotes: 0

Related Questions