Wpf Prism5 PopupUpWidowAction和injection

Wpf Prism5 PopupUpWidowAction和injection,wpf,unity-container,prism,Wpf,Unity Container,Prism,我查看了InteractiveyQuickStart官方示例的一部分 <prism:InteractionRequestTrigger SourceObject="{Binding ItemSelectionRequest, Mode=OneWay}"> <prism:PopupWindowAction> <prism:PopupWindowAction.WindowContent> &l

我查看了InteractiveyQuickStart官方示例的一部分

<prism:InteractionRequestTrigger SourceObject="{Binding ItemSelectionRequest, Mode=OneWay}">
        <prism:PopupWindowAction>
            <prism:PopupWindowAction.WindowContent>
                <views:ItemSelectionView />
            </prism:PopupWindowAction.WindowContent>
        </prism:PopupWindowAction>
    </prism:InteractionRequestTrigger>
在ItemSelectionView的代码隐藏中

问题: 1) 在没有“new”的情况下如何设置DataContext,因为

public ItemSelectionView(ItemSelectionViewModel model)

不起作用。 我需要在ViewModel=>中获得一些服务,我需要调用类似这样的东西

public ItemSelectionViewModel(IEventAggregator eventAggregator)
{
    _eventAggregator=eventAggregator;
}

如果需要为弹出视图模型提供服务,可以使用ServiceLocator获得该服务

public ItemSelectionView()
{
    InitializeComponent();
    DataContext = ServiceLocator.Current.GetInstance<ItemSelectionViewModel>();
}
public ItemSelectionView()
{
初始化组件();
DataContext=ServiceLocator.Current.GetInstance();
}

与其像Brian Lagunas建议的那样使用ServiceLocator来设置ViewModel,不如为ViewModel设置一个无参数构造函数,直接在视图类(XAML或代码隐藏)中设置ViewModel,并在ViewModel本身中使用ServiceLocator来获取ViewModel所需的服务(或其接口)?我建议这样做有两个原因:

  • 在弹出窗口的视图的构造函数中使用ServiceLocator将在设计时在“prism:PopupUpWindowAction.WindowContent”部分中给您一个错误“ServiceLocationProvider必须设置”。(尽管它在运行时运行良好。)
  • 您已经被迫以某种方式绕过依赖注入,所以为什么不简化代码,特别是如果您只需要访问一个服务
所以你可以这样做:

public ItemSelectionViewModel()
{
    _eventAggregator = ServiceLocator.Current.GetInstance<IEventAggregator>();
}
public ItemSelectionViewModel()
{
_eventAggregator=ServiceLocator.Current.GetInstance();
}

如果您只需要使用IEventagegrator对象一次,就没有理由将其指定给字段。只需在需要获取事件聚合器的地方使用ServiceLocator调用,并完全删除显式构造函数。

Awesome!但我遇到了一个小问题:这个弹出窗口应该在加载shell之后出现,它类似于登录表单,所以在shell上的“loaded”事件(=在BootStrapper中的CreateShell()之后)上出现。prism的服务没问题,但共享服务出现了问题,因为在CreateShell()之后加载的模块和我得到了异常。如何在装入shell后弹出窗口?请将此标记为此特定问题的答案,然后将其他问题作为单独的帖子提问。谢谢。我已经离开了PopupIndowAction)
public ItemSelectionView()
{
    InitializeComponent();
    DataContext = ServiceLocator.Current.GetInstance<ItemSelectionViewModel>();
}
public ItemSelectionViewModel()
{
    _eventAggregator = ServiceLocator.Current.GetInstance<IEventAggregator>();
}