首页 > 解决方案 > 与 WPF 窗口一起使用时,MS excel 加载项停止在 excel 功能区中显示

问题描述

我创建了一个 WPF 窗口(非模式),单击 MS excel 加载项功能区中的按钮即可打开该窗口。我遇到了 WPF 窗口中不可编辑的文本框的问题,我试图使用以下给出的解决方案来克服这个问题:MS Excel 插件的 WPF 无模式对话框

现在,WPF窗口中文本框不可编辑的问题得到了解决。但是,一旦我关闭 excel 文件并再次打开它,MS excel 加载项选项卡就会停止显示(此外,当我关闭 excel 文件并重新打开它之前,我可以在任务管理器的后台进程下看到 excel 进程) . 因此,每次打开 excel 文件时,我都需要手动删除并重新添加 excel 加载项。这对于用户环境来说确实是不可接受的。请建议是否有解决方案来克服这个问题。

这是我在按钮(出现在加载项功能区上)单击事件处理程序上编写的代码。

Thread newWindowThread = new Thread(new ThreadStart(() =>
                    {
                        // Create our context, and install it:
                        SynchronizationContext.SetSynchronizationContext(
                            new DispatcherSynchronizationContext(
                                Dispatcher.CurrentDispatcher));
                        
                        Window1 tempWindow = new Window1(ExcelApp.ActiveWorkbook.Name);
                        // When the window closes, shut down the dispatcher
                        tempWindow.Closed += (s, e) =>
                           Dispatcher.CurrentDispatcher.BeginInvokeShutdown(DispatcherPriority.Background);

                        tempWindow.Show();
                        // Start the Dispatcher Processing
                        System.Windows.Threading.Dispatcher.Run();
                    }));

                    // Set the apartment state
                    newWindowThread.SetApartmentState(ApartmentState.STA);
                    // Make the thread a background thread
                    //newWindowThread.IsBackground = true;
                    // Start the thread
                    newWindowThread.Start(); 

标签: wpfexcel-addins

解决方案


有两种方法可以解决这个问题。1)不要使用线程。而是这样做: -

Window1 tempWindow = new Window1(ExcelApp.ActiveWorkbook.Name); tempWindow.ShowDialog();

但由于 ShowDialog() 方法,它阻止了 Excel。

2)按照下面的链接使用 Excel-Dna 在 Excel 中使用 Wpf https://github.com/AddinX/Sample.Wpf/tree/master/src


推荐阅读