![](/img/trans.png)
[英]WPF+PRISM+MEF initializing DownloadedPartCatalogCollection
[英]MEF and WPF without Prism
有人可以告訴我一個在app.xaml.cs文件中構建MEF合成容器的示例,而無需使用棱鏡或控制台應用程序,這沒有問題。
導出有效,但導入無效,我看到的所有示例僅適用於我不想使用的Prism。 如果在App.xaml.cs文件中,導入將起作用,但是我不明白為什么在MainWindow.cs中導入將不起作用,並且一切都在根程序集中。
如果我在MainWindow構造函數中進行合成,則可以編寫它,但是如果可能的話,我想在app.xaml.cs中編寫。
這是一個示例(我實際上正在使用mvvm,但此示例的行為與后面的代碼相同)。
public partial class App : Application
{
public App()
{
ShutdownMode = ShutdownMode = ShutdownMode.OnMainWindowClose;
}
protected override void OnStartup(StartupEventArgs e)
{
base.OnStartup(e);
Compose();
var window = new MainWindow();
window.Show();
}
public void Compose()
{
var catalog = new AggregateCatalog(new AssemblyCatalog(Assembly.GetExecutingAssembly()), new DirectoryCatalog("."));
var container = new CompositionContainer(catalog);
container.ComposeParts(this);
}
}
[Export]
public class MessagePlugin
{
public string GetMessage()
{
return "Successfully composed message";
}
}
public partial class MainWindow : Window
{
[Import]
public MessagePlugin plugin { get; set; }
public MainWindow()
{
InitializeComponent();
Loaded += MainWindow_Loaded;
}
private void MainWindow_Loaded(object sender, RoutedEventArgs e)
{
var p = plugin; <-------------------------------NULL
MessageBox.Show(p.GetMessage());
}
}
public partial class App : Application
{
private CompositionContainer container;
[Import(typeof(Window))]
public Window TheMainWindow { get; set; }
public App()
{
ShutdownMode = ShutdownMode = ShutdownMode.OnMainWindowClose;
}
protected override void OnStartup(StartupEventArgs e)
{
base.OnStartup(e);
TheMainWindow = new MainWindow();
Compose();
Application.Current.MainWindow = TheMainWindow;
Application.Current.MainWindow.Show();
}
public void Compose()
{
var catalog = new AggregateCatalog();
catalog.Catalogs.Add(new AssemblyCatalog(typeof(App).Assembly));
container = new CompositionContainer(catalog);
container.ComposeParts(this);
}
}
[Export(typeof(Window))]公共部分類MainWindow:Window {[Import]公共MessagePlugin插件{get; 組; }
public MainWindow()
{
InitializeComponent();
Loaded += MainWindow_Loaded;
}
private void MainWindow_Loaded(object sender, RoutedEventArgs e)
{
var p = plugin;
if (p != null)
{
MessageBox.Show(p.GetMessage());
}
else
{
MessageBox.Show("Plugin NOT Composed");
}
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.