Dan Harris
Dan Harris

Reputation: 1396

Linking View to ViewModel using DataTemplate for a WPF Application using the MVVM pattern

Current I have some Views linked to ViewModels using code similar to the following:

<Application.Resources>
        <DataTemplate DataType="{ x:Type vm:AgeIndicatorViewModel}">
        <v:AgeIndicatorView />
    </DataTemplate>
</Application.Resources>

I have two questions regarding this:

The most important question is the second really, as at the moment I want to link my ViewModel to my View in this way, as it requires no external libraries etc.

The way my ViewModels are setup, with their Properties and Commands etc is all working already.

Upvotes: 3

Views: 3780

Answers (2)

CodeNaked
CodeNaked

Reputation: 41403

Specifying the implicit DataTemplate like you do in your question does tie your View-Model to a single View. You can override this at any control level though, so you could have:

<Window.Resources>
    <DataTemplate DataType="{x:Type vm:AgeIndicatorViewModel}">
        <v:AgeIndicatorView2 />
    </DataTemplate>
</Window.Resources>

This would change the view applied to a view-model for the given window. This can be done on any control at any level.

The benefit of doing this at the app-level though is that it is applied across all windows in your application. While my example above would only be applied to a single window.

In general, the app resources is the best place to define these. Since if you have multiple Windows (i.e. Window1 and Window2), then your view-model will always pick up your implicit DataTemplate.

Upvotes: 2

Reed Copsey
Reed Copsey

Reputation: 564821

Does this method allow me to only link one View to each View Model (I think it does improse this limitation on me, but want to be sure)

Yes. If you're trying to link multiple ViewModels to multiple Views, you need to encapsulate them within a separate VM, and add a new DataTemplate.

When using this method, where should I put all of my DataTemplate declarations? At the moment there are only a few, and they are all in App.Xaml - Is there a better location for these, or is App.Xaml fine / Best location?

App.Xaml is fine, or really any place in the visual hierarchy above where the DataTemplate will be used.

That being said, if the project gets to be a very large scale project, it's often nicer to start using Merged Resource Dictionaries - this allows you to setup resource dictionaries "near" where you define the View/ViewModel pairs, but then use them at a higher level (ie: merge them into App.Xaml).

Upvotes: 2

Related Questions