This project has moved and is read-only. For the latest updates, please go here.

How should Views and DataTemplates interact?

Apr 17, 2010 at 5:18 PM
Edited Apr 17, 2010 at 5:20 PM

Suppose I have a Customer model, say

    public class Customer
        public string Name { get; set; }
        public string Description { get; set; }
        public int Age { get; set; }

And I have a corresponding CustomerViewModel

    public class CustomerViewModel : ViewModelBase
        public Customer Model
            private set;

        public CustomerViewModel(Customer model)
            Model = model;

In the template example (as well as the Get Started example), we end up creating an ObservableCollection of CustomerViewModels. A CustomerView is never created, but a DataTemplate is created for the CustomerViewModel inside MainWindow.xaml. Is this the CustomerView? How would I go about creating a CustomerView for all future users of my CustomerViewModel? How does the Locator relate to this? What I would like to do is to create a CustomerView which I can then edit in Blend - and have it propagate to any UserControl that holds Customers. (In fact, I would love to have two views, a CustomerView and CustomerEditView...). Can anyone out there advise?

Thanks in advance.







Apr 17, 2010 at 10:50 PM


The DataTemplate is the View for a CustomerViewModel. Note that the CustomerViewModel is a different kind of ViewModel than the MainViewModel. The MainVM is data bound to a view explicitly (through the ViewModelLocator). On the other hand, the CustomerVM is bound to the DataTemplate implicitly. This is done by Silverlight or WPF when you specify that a collection of CustomerVM is the ItemsSource of a list control (such as a ListBox), and that the DataTemplate is the ItemTemplate property of the list control.

Because the binding is made implicitly by SL or WPF, it is not visible anywhere that the DataContext of the DataTemplate is the CustomerVM. However Blend is able to display this in the Data panel when you are editing the ItemTemplate of the ListBox.

In order to get two views (Edit view and normal view), you need to work with the ItemContainerStyle in WPF, and use triggers to switch between the edit mode and the normal mode.

For Silverlight, since triggers are not available, you need to edit the ItemContainerStyle, then edit the ItemControlTemplate and define the appearance of the template for the Selected and SelectedUnfocused states.

Does that make sense?