我有一种感觉,我错过了一些非常重要的东西。我创建了以下代码:
文件:App.xaml
<Application x:Class="HelloWorld.App"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Startup="Application_Startup">
<Application.Resources>
<ResourceDictionary>
<ResourceDictionary.MergedDictionaries>
<ResourceDictionary Source="MainView.xaml" />
</ResourceDictionary.MergedDictionaries>
</ResourceDictionary>
</Application.Resources>
</Application>
Run Code Online (Sandbox Code Playgroud)
文件:MainWindow.xaml
<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:viewmodel="clr-namespace:HelloWorld.ViewModel">
<DataTemplate DataType="{x:Type viewmodel:ViewModel}">
<Window Title="HelloWorld">
<Window.Resources>
<Style TargetType="TextBlock">
<Setter Property="Margin" Value="50"></Setter>
</Style>
</Window.Resources>
<TextBlock Text="TODO" />
</Window>
</DataTemplate>
</ResourceDictionary>
Run Code Online (Sandbox Code Playgroud)
虽然我可以编译代码并且一切看起来都不错。我收到了从<Window Title="HelloWorld">到的灰色摆动线,</Window>并显示消息“无法将窗口置于样式中。”。我想知道我做错了什么?
我应该怎么做才能改进我的代码?顺便说一句,我正在尝试使用 MVVM。
谢谢!
该Window类别:
提供创建、配置、显示和管理窗口和对话框生命周期的能力。
和:
主要用于显示独立应用程序的窗口和对话框。
由于Window元素是顶级元素,它们不能被添加到Content低级元素中。您无法将窗口放入样式错误很明显......您不能Window在 a 中使用a Style,或者DataTemplate在您的情况下使用 a 。
你有几个选择,而不是尝试这样做:
1) 将Window内容放入 a 中DataTemplate,然后在 aContentControl中显示该内容Window:
<DataTemplate DataType="{x:Type viewmodel:ViewModel}">
<!-- Define content -->
</DataTemplate>
Run Code Online (Sandbox Code Playgroud)
...
<ContentControl Content="{Binding ViewModelProperty}" />
Run Code Online (Sandbox Code Playgroud)
2) 使用 aUserControl而不是Window元素:
<DataTemplate DataType="{x:Type viewmodel:ViewModel}">
<UserControl>
<!-- Define Content here -->
</UserControl>
</DataTemplate>
Run Code Online (Sandbox Code Playgroud)