Setting Window.Content to ViewModel - simple data template not working

↘锁芯ラ 提交于 2019-12-12 02:26:32

问题


Trying to get my head around MVVM, and getting a simple window to render its viewmodel as a view via data templating.

in App.xaml:

<Application.Resources>
   <DataTemplate DataType="{x:Type vm:TestViewModel}">
      <vw:TestView />
   </DataTemplate>
</Application.Resources>

View definition:

<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>

In MainWindowViewModel:

private void onOpenTestView(object sender)
{
   Window w = new Window();
   w.Content = new TestViewModel();
   w.Show();
}

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.

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?

Cheers, Jeremy

EDIT: FIXED (Can't answer for 8 hours)

Due to MS Bug where resources not being read unless at least one style is set.

See http://connect.microsoft.com/VisualStudio/feedback/details/553528/defaultstylekey-style-not-found-in-inner-mergeddictionaries


回答1:


Due to MS Bug where resources not being read unless at least one style is set.

See http://connect.microsoft.com/VisualStudio/feedback/details/553528/defaultstylekey-style-not-found-in-inner-mergeddictionaries



来源:https://stackoverflow.com/questions/6108346/setting-window-content-to-viewmodel-simple-data-template-not-working

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!