Prism 6.1.0 MefBootstrapper的实现:CreateShell方法抛出异常

时间:2017-01-31 13:35:29

标签: c# wpf prism mef

我第一次使用Prism 6.1.0。 我创建了一个新的WPF项目,试着品尝最新的棱镜。

我的shell看起来像这样:

<Window x:Class="Prism.Shell"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    xmlns:local="clr-namespace:Prism"
    mc:Ignorable="d"
    Title="Shell"
    Height="300"
    Width="300">
<Grid Background="HotPink"></Grid>

using System.ComponentModel.Composition;
using System.Windows;

namespace Prism
{
    /// <summary>
    /// Interaction logic for Shell.xaml
    /// </summary>
    [Export]
    public partial class Shell : Window
    {
        public Shell()
        {
            InitializeComponent();
        }
    }
}

引导程序:

using Prism.Mef;
using System.ComponentModel.Composition.Hosting;
using System.Windows;

namespace Prism
{
    public class MyBootstrapper : MefBootstrapper
    {
        protected override DependencyObject CreateShell()
        {
            return Container.GetExportedValue<Shell>();
        }
        protected override void InitializeShell()
        {
            base.InitializeShell();
            Application.Current.MainWindow = (Window)Shell;
            Application.Current.MainWindow.Show();
        }
        protected override void ConfigureAggregateCatalog()
        {
            base.ConfigureAggregateCatalog();
            AggregateCatalog.Catalogs
                .Add(new AssemblyCatalog(typeof(MyBootstrapper).Assembly));
        }
    }
}

和App c#代码是:

using System.Windows;
namespace Prism
{
    /// <summary>
    /// Interaction logic for App.xaml
    /// </summary>
    public partial class App : Application
    {
        protected override void OnStartup(StartupEventArgs e)
        {
            base.OnStartup(e);
            (new MyBootstrapper()).Run();
        }
    }
}

这一行之后: enter image description here 我有一个例外: 抛出 异常:PresentationCore.dll中的'System.InvalidOperationException' 附加信息:调用线程必须是STA,因为许多UI组件都需要这个。 enter image description here

有人知道如何解决这个问题吗?

1 个答案:

答案 0 :(得分:0)

异常说你的窗口构造函数是由另一个线程调用的。在WPF世界中,每个控件:窗口,按钮等必须由一个名为STAThread的特殊线程创建。此外,只有STAThread可以访问UI控件(如果另一个线程执行此操作,则会抛出相同的InvalidOperationExcepiotion)。所以看起来你在某个地方调用了一个新线程。我在代码中看不到错误,我也不知道你的容器是否启动任何线程。但请确保您不在代码中创建任何可疑线程。

还要在App.xaml中查找StartupURI。如果使用DI容器,则不应设置它。但我想不是这个。

我创建了一个示例应用,我复制了你的代码并且它有效。所以你的错误很奇怪。