将Window.Content设置为ViewModel-简单数据模板不起作用 [英] Setting Window.Content to ViewModel - simple data template not working
问题描述
试图绕过MVVM,并获得一个简单的窗口,通过数据模板将其视图模型呈现为视图。
Trying to get my head around MVVM, and getting a simple window to render its viewmodel as a view via data templating.
:
<Application.Resources>
<DataTemplate DataType="{x:Type vm:TestViewModel}">
<vw:TestView />
</DataTemplate>
</Application.Resources>
视图定义:
<UserControl x:Class="MyNamespace.TestView"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
mc:Ignorable="d"
d:DesignHeight="300" d:DesignWidth="300">
<Grid>
<TextBlock>TESTING</TextBlock>
</Grid>
</UserControl>
在MainWindowViewModel中:
In MainWindowViewModel:
private void onOpenTestView(object sender)
{
Window w = new Window();
w.Content = new TestViewModel();
w.Show();
}
运行该应用程序会在一个带有 MyNamespace.TestViewModel字符串的窗口中,而不是测试,这将推断未找到我的数据模板。
Running the app results in a window with a "MyNamespace.TestViewModel" string, instead of "TESTING", which would infer my data template is not being found.
我对这一切都很陌生,所以我错过了明显的东西吗?我不认为这是字符串匹配的问题,因为如果我故意在XAML中拼写错误的视图或模型,那么它将无法编译。
I am very new to all this so am I missing something obvious? I don't think it's a string matching issue since if I deliberately misspell the view or model in the XAML then it doesn't compile.
我的新窗口应该能够可以访问我的应用程序资源(以及我的数据模板)好吗?
Should my new window be able to access my app resources (and thus my datatemplate) ok?
干杯,
Jeremy
Cheers, Jeremy
编辑:已修复(无法回答8小时)
FIXED (Can't answer for 8 hours)
由于MS错误,除非至少设置了一种样式,否则无法读取资源。
Due to MS Bug where resources not being read unless at least one style is set.
推荐答案
由于MS Bug,除非设置了至少一种样式,否则无法读取资源。
Due to MS Bug where resources not being read unless at least one style is set.
这篇关于将Window.Content设置为ViewModel-简单数据模板不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!