简单实例说明
View Code
1 [Export] 2 public partial class TitleView : UserControl 3 { 4 public TitleView() 5 { 6 InitializeComponent(); 7 } 8 [Import( " TitleViewModel ")] 9 public TitleViewModel ViewModel { get { return this.DataContext as TitleViewModel; } set { this.DataContext = value; } } 10 }
如果在module中采用如下方式调用 var titleview = ServiceLocator.Current.GetInstance<TitleView>(); 不会有错误.
而如果把上面的[Export]改为[Export("TitleView")] 则会引发异常
Activation error occured while trying to get instance of type TitleView, key ""
解决办法是将调用的方法更改为
var titleview = ServiceLocator.Current.GetInstance(typeof(TitleView), "TitleView");
同样我们在使用RegisterViewWithRegion注册View时如果也发生类似错误也可用此法解决,对应调用方法如下:
this.regionManager.RegisterViewWithRegion(RegionNames.MainTitleRegion, () => { return ServiceLocator.Current.GetInstance(typeof(TitleView), "TitleView"); });