我正在使用 PRISM4 MVVM 模式,并且视图已成功加载并在应用程序启动时显示在适当的区域。当应用程序启动时,ViewModel 会在视图加载时自动初始化。但是,如果我尝试在新选项卡(新区域)上注入新视图,则不会初始化新视图的 ViewModel。这是视图注入的代码:
IRegion region = regionManager.Regions["RegionNameGoesHere"];
var pane = new Views.ABCView() {Tag = id};
regionManager.Regions["RegionNameGoesHere"].Add(pane);
上面的代码会打开一个新选项卡并加载新视图,但它不会初始化 ViewModel。控件的每个选项卡都是一个新区域(选项卡控件有一个 RegionAdapter)。
这是视图背后的代码:
using System.ComponentModel.Composition;
using System.Diagnostics.CodeAnalysis;
using System.Windows.Controls;
using Telerik.Windows.Controls;
using Telerik.Windows.Controls.Docking;
namespace Company.Application.Module.Assembly.Views
{
[Infrastructure.Behaviours.ViewExport("ABCView")]
[PartCreationPolicy(CreationPolicy.NonShared)]
public partial class ABCView : RadPane
{
public ABCView()
{
this.InitializeComponent();
}
/// <summary>
/// Sets the ViewModel.
/// </summary>
/// <remarks>
/// This set-only property is annotated with the <see cref="ImportAttribute"/> so it is injected by MEF with
/// the appropriate view model.
/// </remarks>
[Import]
[SuppressMessage("Microsoft.Design", "CA1044:PropertiesShouldNotBeWriteOnly", Justification = "Needs to be a property to be composed by MEF")]
ABCViewModel ViewModel
{
set
{
this.Decorator.DataContext = value;
//this.DataContext = value;
}
}
}
}
这是带有一些属性和事件的 ViewModel。我在上面的代码中遗漏了一些东西来初始化下面的 ViewModel。非常感谢任何建议。
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Collections.Specialized;
using System.ComponentModel.Composition;
using System.Linq;
using System.ServiceModel;
using System.ServiceModel.Description;
using System.Text;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Xml;
using System.Xml.XPath;
using System.Windows.Data;
using Microsoft.Practices.Prism.Commands;
using Microsoft.Practices.Prism.Events;
using Microsoft.Practices.Prism.Regions;
using Microsoft.Practices.Prism.ViewModel;
namespace Company.Application.Module.Assembly.Views
{
[Export(typeof(ABCViewModel))]
[PartCreationPolicy(CreationPolicy.NonShared)]
public class ABCViewModel : NotificationObject
{
private readonly IRegionManager regionManager;
[ImportingConstructor]
public ABCViewModel(IRegionManager regionManager)
{
// Event Aggregator
//this.eventAggregator = eventAggregator;
// Region Manager
this.regionManager = regionManager;
}
#region P R O P E R T I E S
#region E V E N T S
}
}