Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/wpf/14.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Wpf 是否可以将数据模板应用于页面?_Wpf_Mvvm_Datatemplate_Viewmodel - Fatal编程技术网

Wpf 是否可以将数据模板应用于页面?

Wpf 是否可以将数据模板应用于页面?,wpf,mvvm,datatemplate,viewmodel,Wpf,Mvvm,Datatemplate,Viewmodel,我试图遵循此处列出的MVVM模式:我的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> 数据模板应用于内容,在大多数情况

我试图遵循此处列出的MVVM模式:我的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>


数据模板应用于内容,在大多数情况下,内容要么是ContentControl的Content属性,要么是ItemsControl的Items/ItemsSource属性。页面不是从ContentControl派生的(UserControl是),因此无法将DataTemplate应用于其内容


从你在这里做的事情来看,这听起来不像是你想要做的。看起来您正在尝试使用DataTemplate中的某个页面,而这正是错误告诉您的。页面被视为窗口,因为它是一个根容器,用于在xaml文件中定义可视内容。UserControl具有类似的用途,但可以插入布局的任何位置。如果你改变大众:供应商是一个用户控件,应该摆脱这个特定的错误,但是你也应该考虑你是否从拥有USER控件获得任何东西,而不是仅仅把它的内容直接放在数据板上——这有助于阻止代码的背后,并强迫你正确使用你的VIEW模型。

@迈克,您必须将标记的元素标记为代码,否则它们将不会呈现,人们也不会理解您的问题-这次我为您做了这些(-):我最初的目标是使用一个基于导航的WPF应用程序,在不同的页面上导航。如果我使用UserControls,我将如何完成相同类型的事情?单击菜单中的一个项目,然后显示该UserControls。我会创建一个布局项目,例如Grid,然后将UserControls添加到Grid中或从中添加到Grid中吗看起来您可能混淆了这里的一些概念。您使用页面的目标似乎是正确的-它们是专门为支持基于URI的导航而设计的。我认为,在尝试使用DataTemplate的地方,您实际上希望将页面的DataContext设置为VendorsViewModel类的实例。这就是允许您进行bi的原因从页面的XAML中nd到VM的属性,就像您在上一个代码段中所做的那样。您可以从XAML或代码(如外部工厂或演示者)在页面上设置DataContext。
<Window.Resources>
     <ResourceDictionary Source="MainWindowResources.xaml"/>
</Window.Resources>
<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>