views:

92

answers:

1

I'm trying to follow the MVVM pattern laid out here: http://msdn.microsoft.com/en-us/magazine/dd419663.aspx#id0090097 I have this in my MainWindowResources.xaml file:

<DataTemplate DataType="{x:Type vm:VendorsViewModel}">
        <vw:Vendors/>  <--- I get a "Can't put a page in a style" error in blend with this
</DataTemplate>

and I've got this in my MainWindow.xaml file

<Window.Resources>
     <ResourceDictionary Source="MainWindowResources.xaml"/>
</Window.Resources>

The mainWindow.xaml file contains a menu on the left and page holder on the right. Can I apply a dataTemplate to a <Page>? Or does it have to be a <UserControl>? As it stands, nothing is being data bound, here's what I have on the page that I want to have the viewmodel applied to:

<Custom:DataGrid Margin="0,30,0,0" d:LayoutOverrides="Width" ItemsSource="{Binding Path=AllVendors, Mode=Default}" >
     <Custom:DataGrid.Columns>
    <Custom:DataGridTextColumn Header="Company Name" Binding="{Binding Path=Name}" />
    </Custom:DataGrid.Columns>
</Custom:DataGrid>
+2  A: 

DataTemplates are applied to Content, which in most cases is either the Content property of a ContentControl or the Items/ItemsSource property of an ItemsControl. Page is not derived from ContentControl (UserControl is) so a DataTemplate can't be applied to its Content.

From what you're doing here it doesn't sound like that's what you're trying to do though. It looks like you're trying to use a Page in a DataTemplate which is what the error is telling you. Page is treated like Window in that it is a root container that is intended to have visual Content defined in a xaml file. UserControl has a similar purpose but can be inserted anywhere into a layout. If you change vw:Vendors to be a UserControl that should get rid of this specific error but you should also consider whether you're gaining anything from having the UserControl instead of just putting its content directly into the DataTemplate - this can help discourage code-behind and force you to use your ViewModel correctly.

John Bowen
My original aim was to use a navigation based WPF application, with different Pages I navigate to and from. If I were to use UserControls, how would I accomplish the same type of thing? Where I click an item in a menu, and that UserControl is displayed. Would I create a layout item such as Grid, then add the usercontrol to and from the Grid?
Mike
It seems like you might be confusing some concepts here. Your goal for using Pages seems correct - they're specifically designed to support URI based navigation. I think where you were trying to use a DataTemplate, you actually want to be setting the DataContext of your Page to an instance of your VendorsViewModel class. This is what allows you to bind to properties of your VM from the Page's XAML like you're doing in the last code snippet. You can set the DataContext on the Page either from XAML or from code (like an external factory or presenter).
John Bowen