首页 / 软件开发 / .NET编程技术 / 从WinForm程序中显示WPF Window出现“The URI prefix is not recognized”异
从WinForm程序中显示WPF Window出现“The URI prefix is not recognized”异2010-11-20 cnblogs Erich Wang从WinForm程序中显示WPF Window出现“The URI prefix is not recognized”异常的解决方法从WinForm App中显示WPF窗口的代码:MyWindow wpfWindow = new MyWindow();
WindowInteropHelper wih = new WindowInteropHelper(wpfWindow);
wih.Owner = ownerHwnd;
wpfWindow.ShowDialog();
一般情况下,这都可以正常工作。但是如果在MyWindow的代码(不是XAML)中需要显示加载其他xaml文件(可 能是资源文件):_dictionary.Source = new Uri ("/RibbonControlsLibrary;component/Themes/RibbonWindow.xaml" , UriKind.Relative);
你在new MyWindow()就会得到NotSupportedException:"The URI prefix is not recognized". 有两种方法来解决这个问题:1.如果你有MyWindow的源代码,添加前缀pack://application:,,,_dictionary.Source = new Uri ("pack://application:,,,/RibbonControlsLibrary;component/Themes/R ibbonWindow.xaml", UriKind.Relative);
2.如果MyWindow是第三方提供的,你就需要在new MyWindow()之前加上下面 的语句:System.Windows.Application app = new System.Windows.Application();
app.ShutdownMode = System.Windows.ShutdownMode.OnExplicitShutdown;
分析Applicaiton的源代码其实就会发现,在它的静态构造函数中有下面的代 码:// Add an instance of the ResourceContainer to PreloadedPackages so that PackWebRequestFactory can find it
// and mark it as thread-safe so PackWebResponse won"t protect returned streams with a synchronizing wrapper
PreloadedPackages.AddPackage(PackUriHelper.GetPackageUri (BaseUriHelper.PackAppBaseUri), new ResourceContainer(), true);
它的作用其实就是在后面的Uri定位过程中自动添加必要的 "pack://application:,,,"由于app.ShutdownMode的缺省值是OnLastWindowClose,这会在程序中的最后 一个Wpf窗口关闭时自动关闭Wpf Application,如果你需要反复显示关闭Wpf窗口 ,有必要更改其值。在使用第二种方法的过程中其实你会注意到我并没有调用app.Run方法,按我 的理解完全没有必要调用,因为我所需要的只是Application的静态构造函数进 行必要的初始化:PreloadedPackages.AddPackage(...)。