3

What's the value of using a DataTemplate to assign a ViewModel to a View? I see lot's of code that looks like this and am doing the same myself.

ViewResources.xaml

<DataTemplate DataType="{x:Type vm:GenericViewModel}"> <vw:GenericView /> </DataTemplate> 

View.xaml

<ContentControl Content="{Binding Generic}" /> 

What are the advantages compared to displaying the View and binding to the DataContext?

View.xaml

<vw:GenericView DataContext="{Binding Generic}" /> 

At a minimum this appears to require less code and also plays "nicer" with the designer. I can see the need for a DataTemplate(say you're styling a TextBlock or something simple), but once you have created a View what is the point?

7
  • 3
    The idea is that you can have a single, generic view "container" and leverage WPF's implicit template support to automatically inject the view which corresponds to the view model provided as content. I've never personally cared for this approach, but it has the virtue of being quick and easy to get up and running. Commented Oct 14, 2014 at 16:21
  • @MikeStrobel I've considered that as well, at times it makes sense. Binding to the Content property of a GroupBox or similar seems cleaner to me with a DataTemplate, but many other times I feel like I'm using a DataTemplate out of habit vs necessity. Commented Oct 14, 2014 at 16:25
  • I think the idea that every MVVM app needs a navigation system that can locate and show the appropriate view whenever you try to navigate to a new view model, and this technique simply uses WPF's template system to do most of that work for you. It's far from ideal, but it might help you get your first prototype up and running faster. You'll probably want something more powerful long before you ship, though. Commented Oct 14, 2014 at 16:30
  • Related (possibly duplicate?): stackoverflow.com/a/19865031/643085 Commented Oct 14, 2014 at 17:02
  • 1
    Consider the case where you have a listview bound to a List of type IThing, where IThing is an interface. You have two classes, Fred and Barney, both of which implement IThing. You create different DataTemplates, one of which has DataType Fred, and one has DataType Barney. Then, you add a number of items, some Fred, some Barney, to your List<IThing>. The listview renders the Fred items with the Fred datatemplate, the Barney items with the Barney datatemplate, without you having to write any logic. Commented Oct 15, 2014 at 0:30

0

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.