MVVM-PRISM,如何在region / ItemsControl中显示视图的多个实例

时间:2010-10-19 09:25:56

标签: mvvm dependency-injection prism itemscontrol regions

我正在为基于MVVM,CAL和PRISM的应用程序构建模块。我对这些概念都很陌生,试图了解所有模式,现在我正在努力解决以下问题:

我需要创建同一View的多个实例。每个视图都需要绑定到它自己的ViewModel,其中包含该特定视图的数据。更详细一点,这是我的情景:

我需要在OrdersView.xaml中放置的区域内显示OrdersDetailsView.xaml的多个实例。我有一个OrdersView XAML,它包含一个如下定义的ItemsControl标记:

<ItemsControl x:Name="OrdersItemsControl" BorderThickness="0" 
cal:RegionManager.RegionName="OrdersRegion" Margin="0,10,0,10">

您可以理解 - 在OrdersView的ItemsControl中,我想显示OrderDetailsView的多个实例。我能够以下面描述的硬编码方式添加一个 OrderDetailsView,但是将多个视图和数据加载到该区域的正确/首选方法是什么?

Dim OrdersRegion = _RegionManager.Regions("OrdersRegion")
Dim view = _Container.Resolve(Of OrdersDetailsView)()
Dim viewmodel = _Container.Resolve(Of OrdersDetailsViewModel)()

view.ApplyModel(viewmodel)
OrdersRegion.Add(view, "OrdersDetailsView")
OrdersRegion.Activate(view) 

编辑:

为什么这段代码给了我2 OrdersDetailsView和订单ZZZ,我希望我得到一个Orders XXX和一个Orders ZZZ的视图:

    Dim OrdersRegion = _RegionManager.Regions("OrdersRegion")

    Dim viewX = _Container.Resolve(Of OrdersDetailsView)()
    Dim viewmodelX = _Container.Resolve(Of OrdersDetailsViewModel)()

    viewmodelX.OrdersName = "Orders XXX"
    viewX.ApplyModel(viewmodelX)


    Dim viewZ = _Container.Resolve(Of OrdersDetailsView)()
    Dim viewmodelZ = _Container.Resolve(Of OrdersDetailsViewModel)()

    viewmodelZ.OrdersName = "Orders ZZZ"
    viewZ.ApplyModel(viewmodelZ)

    OrdersRegion.Add(viewX, "OrdersDetailsViewX")
    OrdersRegion.Add(viewZ, "OrdersDetailsViewZ")

EDIT2:

Public Sub Initialize() Implements Microsoft.Practices.Composite.Modularity.IModule.Initialize
    RegisterServices()

    container.Resolve(Of IOrdersView)()
    container.Resolve(Of IOrdersViewModel)()
    container.Resolve(Of IOrdersDetailsView)()
    container.Resolve(Of IOrdersDetailsViewModel)()

End Sub

Private Sub RegisterServices()
    container.RegisterType(Of IOrdersViewModel, OrdersViewModel)(New ContainerControlledLifetimeManager())
    container.RegisterType(Of IOrdersView, OrdersView)()

    container.RegisterType(Of IOrdersDetailsViewModel, OrdersDetailsViewModel)(New ContainerControlledLifetimeManager())
    container.RegisterType(Of IOrdersDetailsView, OrdersDetailsView)()
End Sub

1 个答案:

答案 0 :(得分:1)

是的,这是正确的做法。当然,您必须重复此代码才能创建新的V-VM对:

Dim view = _Container.Resolve(Of OrdersDetailsView)()
Dim viewmodel = _Container.Resolve(Of OrdersDetailsViewModel)()

view.ApplyModel(viewmodel)

此外,无需调用Activate,因为当主机控件是ItemsControl(AllActiveRegion)时,所有视图都处于活动状态。

我希望这会有所帮助。