使用 Prism 时如何允许 WPF 解析 Window 控件的 ContentTemplate?

How to allow WPF to resolve ContentTemplate for a Window control when using Prism?

我正在尝试创建一个简单的基于 WPF 的对话框类型控件 Window class(Popup 在这里不起作用)。 在我的应用程序中,我在 Application.Resources:

中注册了一个 DataTemplate
<Application.Resources>
    <DataTemplate  DataType="{x:Type local:EntitySelectorViewModel}">
        <local:EntitySelector></local:EntitySelector>
    </DataTemplate>        
</Application.Resources>

在我的 Window 控件中,我设置了 Window.Content 并且我希望 WPF 会根据上面显示的 DataTemplate 注册将 ContentTemplate 设置为 EntitySelector 的一个实例:

[Export(typeof(EntitySelectorDialog))]
[PartCreationPolicy(CreationPolicy.NonShared)]
public partial class EntitySelectorDialog : Window
{
    [ImportingConstructor]
    public EntitySelectorDialog(EntitySelectorViewModel vm)
    {
        InitializeComponent();

           // DataContext = vm;  // does not work

           // EDIT: Per two answers shown below the following should work but it does not.
           Content = vm;  
    }
}

问题是 WPF 没有解析 ContentTemplate,即没有创建 EntitySelector 的实例。此外,当我查看 EntitySelectorDialog 的 XAML 时,我看到 shell 的一个实例已被注入 进入 Window 控件 (EntitySelectorDialog)。

我对 Prism 的了解还不够,不知道我是想随波逐流并以某种方式使用 shell,还是想完全阻止 Prism 注入它。我认为在这个特定的控件中我不需要它,所以如果只是防止 Prism 注入它是有意义的,我会更喜欢这条路线。

郑重声明,我已尝试从我的 Window 控件中删除 Prism 属性,并手动新建组件。这似乎没有效果 - Prism 仍然设法以某种方式注入 shell 并且我的 ContentTemplate 未解析。

Window 控件 (EntitySelectorDialog) 除了 Window 声明本身之外没有要显示的 XAML - 我希望内容完全来自 ContentTemplate (EntitySelector)。

我看过这个可能会提供答案,但我不知道如何在不破坏应用程序其余部分的情况下实现它:

Getting Unity to Resolve views in XAML

您需要将vm设置为EntitySelectorDialog.Content以触发WPF根据类型解决DataTemplate。所以你要么添加

Content = vm;

在构造函数中或添加

Content = {Bing}

在 Xaml.

将 window 的 Content 设置为 ContentControl 并将此 Content 属性 设置或绑定到视图模型:

[Export(typeof(EntitySelectorDialog))]
[PartCreationPolicy(CreationPolicy.NonShared)]
public partial class EntitySelectorDialog : Window
{
    [ImportingConstructor]
    public EntitySelectorDialog(EntitySelectorViewModel vm)
    {
        InitializeComponent();
        DataContext = vm;
        Content = new ContentControl() { Content = vm };
    }
}