wpf - UriFormatException : Invalid URI: Invalid port specified

标签 wpf xaml resources uri

下面用作 Uri 参数的程序集限定字符串在 XAML 中工作,但在代码中使用时会出现错误。

我尝试了各种 UriKind,结果都相同。我该如何解决这个问题?

[Test]
public void LargeImageSource_IsKnown()
{
var uri = new Uri(
        "pack://application:,,,/" + 
        "MyAssembly.Core.Presentation.Wpf;component/" + 
        "Images/Delete.png", UriKind.RelativeOrAbsolute);

Assert.That(
        _pickerActivityCollectionVm.DeleteActivityCommand.LargeImageSource,
        Is.EqualTo(uri));
}

System.UriFormatException : Invalid URI: Invalid port specified.
at System.Uri.CreateThis(String uri, Boolean dontEscape, UriKind uriKind)
at System.Uri..ctor(String uriString, UriKind uriKind)

更新

根据 Thomas 的出色回答和我自己对可读性的评论,我最终在 BaseTestFixture 类中使用了以下内容。希望这对其他人有帮助。

    protected virtual void OnFixtureSetUp() {
        // logging, other one time setup stuff...

        const string scheme = "pack";
        if (!UriParser.IsKnownScheme(scheme)) {
            Assert.That(PackUriHelper.UriSchemePack, Is.EqualTo(scheme));
        }
    }

最佳答案

这是因为您在 pack:// 方案尚未注册时执行此代码。当您创建 Application 对象时会注册此方案。您可以在测试装置的设置中添加此代码:

[SetUp]
public void Setup()
{
    if (!UriParser.IsKnownScheme("pack"))
        new System.Windows.Application();
}
<小时/>

编辑:实际上,似乎 pack:// 方案已在 PackUriHelper 类的类型初始值设定项中注册(该类恰好由 Application 使用) 类)。因此,实际上您不需要创建 Application 的实例,只需访问 PackUriHelper 的静态成员即可确保类型初始值设定项已运行:

[SetUp]
public void Setup()
{
    string s = System.IO.Packaging.PackUriHelper.UriSchemePack;
}

关于wpf - UriFormatException : Invalid URI: Invalid port specified,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6005398/

相关文章:

c# - DataGrid 方法 DataSource 未找到

.net - silverlight 组件位置的 CSS 问题。无法设置我想要的高度

c# - 如何绑定(bind)要在 xaml 中使用的值

wpf - 在 WPF textBlock 中用缩进换行文本

Android - 不透明度淡入淡出可绘制

android - Galaxy Tab 和 Motorola XOOM 的绘图和布局

c# - 以编程方式将 xml 文档绑定(bind)到 WPF 中的 TreeView

具有自定义模板的 WPF 切换按钮不接受在正确区域中的单击

c# - 如何为模板控件创建自定义属性

hadoop - 元模型hadoop-ExcelDataContext的HdfsResource问题