Is it possible to apply a DataTemplate to a page?

I am trying to follow the MVVM pattern outlined here: http://msdn.microsoft.com/en-us/magazine/dd419663.aspx#id0090097 I have this in MainWindowResources.xaml:

<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 got this in MainWindow.xaml

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

The mainWindow.xaml file contains a menu on the left and a page holder on the right. Can I apply dataTemplate to <Page> ? Or should it be <UserControl> ? Be that as it may, nothing is tied to data, here is what I have on the page to which I want to apply a view model:

 <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> 
+4
source share
1 answer

DataTemplates are applied to Content, which in most cases is either the Content property of the ContentControl property or the Items / ItemsSource of the ItemsControl element. The page is not derived from the ContentControl (UserControl), so the DataTemplate cannot be applied to its Content.

From what you are doing here, it doesn’t look like what you are trying to do. It looks like you are trying to use a page in a DataTemplate, which is what the error tells you. The page is treated like Window in that it is the root container that is intended for the visual content defined in the xaml file. UserControl has a similar purpose, but can be inserted anywhere in the layout. If you change vw: Providers should be a UserControl that should get rid of this particular error, but you should also think about whether you get something from UserControl instead of just putting its contents directly in the DataTemplate, - this can help evade the code - and make you use the ViewModel correctly.

+3
source

Source: https://habr.com/ru/post/1302019/


All Articles