【发布时间】:2015-02-24 20:06:49
【问题描述】:
我正在使用 Prism + MEF
我有相当简单的应用程序。
我有一个区域为“Region1”的外壳。
将模块作为单独的项目使用MyUserControl.xaml、MyUserControlVM.cs 和ModuleA.cs。此用户控件必须显示在 Shell--> Region1 中。为此,我已将此用户控件添加到 ModuleA.cs 的区域中
现在MyUserControlVM 不会注入UserControl Datacontext。
[ModuleExport(typeof(ModuleA))]
public class ModuleA : IModule
{
public void Initialize()
{
var regionManager = ServiceLocator.Current.GetInstance<IRegionManager>();
regionManager.Regions["Region1"].Add(new MyUserControl());
}
}
MyuserControl.Xaml
<StackPanel>
<Label Content="{Binding Message}" Height="38" HorizontalAlignment="Left" Name="label1" VerticalAlignment="Top" Width="193" Background="#FFD8CFCF" />
<Label Content="ABC"></Label>
</StackPanel>
MyUserControl.Xaml.cs
public partial class MyUserControl : UserControl
{
public MyUserControl()
{
InitializeComponent();
}
[Import]
public MyUserControlVM ViewModel
{
get { return this.DataContext as MyUserControlVM; }
set { this.DataContext = value; }
}
}
MyUserControlVM.cs
[Export(typeof(MyUserControlVM))]
[PartCreationPolicy(CreationPolicy.NonShared)]
public class MyUserControlVM : INotifyPropertyChanged
{
private string _message;
public string Message
{
get { return _message; }
set
{
_message = value;
NotifyPropertyChanged("Message");
}
}
public event PropertyChangedEventHandler PropertyChanged;
private void NotifyPropertyChanged(string propertyName)
{
if(PropertyChanged != null)
PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
}
Shell.Xaml 中定义的区域:
<Grid>
<ContentControl Name="Region1" regions:RegionManager.RegionName="Region1" Margin="70">
</ContentControl>
</Grid>
App.xaml.cs 是这样的
protected override void OnStartup(StartupEventArgs e)
{
base.OnStartup(e);
var bootstrapper = new Bootstrapper();
bootstrapper.Run();
}
BootStrapper 是这样的
public class Bootstrapper : MefBootstrapper
{
protected override DependencyObject CreateShell()
{
return Container.GetExportedValue<Shell>();
}
protected override void InitializeShell()
{
base.InitializeShell();
App.Current.MainWindow = (Window)Shell;
App.Current.MainWindow.Show();
}
protected override void ConfigureAggregateCatalog()
{
base.ConfigureAggregateCatalog();
AggregateCatalog.Catalogs.Add(new AssemblyCatalog(typeof(Shell).Assembly));
AggregateCatalog.Catalogs.Add(new AssemblyCatalog(typeof(ModuleLibrary.ModuleA).Assembly));
}
}
请帮助我哪里做错了。
【问题讨论】: