【问题标题】:How to allow WPF to resolve ContentTemplate for a Window control when using Prism?使用 Prism 时如何允许 WPF 为 Window 控件解析 ContentTemplate?
【发布时间】:2018-08-23 19:26:45
【问题描述】:

我正在尝试创建一个基于 WPF Window 类的简单对话框类型的控件(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 的一个实例已被注入 进入窗口控件(EntitySelectorDialog)。

我对 Prism 了解得不够多,不知道我是否想顺其自然并以某种方式使用 shell,或者我是否想完全阻止 Prism 注入它。我认为在这个特定的控制中我不需要它,所以如果阻止 Prism 注入它是有意义的,我会更喜欢这条路线。

作为记录,我已尝试从 Window 控件中删除 Prism 属性,并手动新建了组件。这似乎没有效果 - Prism 仍然设法以某种方式注入外壳,并且我的 ContentTemplate 没有解决。

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

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

Getting Unity to Resolve views in XAML

【问题讨论】:

  • 是什么阻止您使用ViewModelLocator?为什么 MEF - Unity 或任何其他真正的 DI 容器更适合?创建和显示窗口的代码是什么样的?

标签: c# wpf prism


【解决方案1】:

将窗口的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 };
    }
}

【讨论】:

  • 谢谢,我认为你的回答是正确的,但它仍然不起作用。
  • 会发生什么?你在窗口中看到了什么?
  • 我什么也没看到。未创建视图 (EntitySelector) 的实例。
  • 如果将 Content 设置为 TextBlock 会怎样?你看到了吗?
  • 并且你已经确认你实际上在窗口的构造函数中得到了一个EntitySelectorViewModel?
【解决方案2】:

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

Content = vm;

在构造函数中或添加

Content = {Bing}

在 Xaml 中。

【讨论】:

  • 谢谢亚历克斯 - 你当然是正确的,但是 WPF 不合作。它不起作用。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2010-10-05
  • 1970-01-01
  • 2013-07-10
  • 2017-12-17
相关资源
最近更新 更多