Uri 为 WPF 样式 uri 抛出无效端口

Uri throws invalid port for WPF style uri

我正在尝试使用 wpf 样式 uri 在代码中初始化 BitmapImage 实例。

BitmapImage icon = new BitmapImage(new Uri("pack://application:,,,/MyAssembly;component/Icons/someIcon.ico", UriKind.Absolute));

但问题是 new Uri 抛出 System.UriFormatException

Invalid URI: Invalid port specified.

我做错了什么?

这里的问题是您试图在非普通 WPF 应用程序的应用程序中创建 UriUri 有一些内置 'schemes' 已注册到 UriParser

The UriParser class enables you to create parsers for new URI schemes. You can write these parsers in their entirety, or the parsers can be derived from well-known schemes (HTTP, FTP, and other schemes based on network protocols).

WPF 在创建 System.Windows.Application 时为 'pack' 方案添加一个解析器,这是 WPF 应用程序的正常入口点。在您的情况下,您只需在组合根目录中添加对此的调用:

new System.Windows.Application();

我们可以使用下面的代码

UriParser.Register(new GenericUriParser(GenericUriParserOptions.GenericAuthority), "pack", -1);

在尝试创建 uri 之前。