【问题标题】:BitmapImage throwing NotImplementedException on EndInit()BitmapImage 在 EndInit() 上抛出 NotImplementedException
【发布时间】:2017-10-11 18:32:21
【问题描述】:

我正在尝试从 WPF 窗口中的文件加载位图图像,但在下面的 EndInit() 行中出现异常

BitmapImage img = new BitmapImage();
img.BeginInit();
img.CacheOption = BitmapCacheOption.OnLoad;
img.UriSource = PackUriHelper.Create(new Uri(@"pack://application:,,,/Images/TestImage.png", UriKind.Absolute));
img.EndInit();
img.Freeze();

异常堆栈跟踪:

有什么想法吗?如果它完全相关,则此 WPF 窗口托管在本机应用程序中。

【问题讨论】:

  • 请将 StackTrace 作为文本发布,不要作为图片发布
  • PackUriHelper.Create 在这里似乎没有意义,因为您已经有了 Pack URI。 img.UriSource = new Uri(@"pack://application:,,,/Images/TestImage.png") 在标准 WPF 应用程序中就足够了。对于非 WPF 应用程序,this answer 可能会有所帮助。
  • MSDN - 如果我不使用 PackUriHelper,我会得到一个不同的异常“无法识别 URI 前缀”

标签: c# wpf


【解决方案1】:

我现在已经开始工作了——我相信这个异常被抛出了,因为我试图在任何 xaml 资源加载之前解析/加载BitmapImage。我强制将 BitmapImage 初始化到我绑定的 Image 属性的 getter 中,它不再抛出。

我还注意到我能够直接从 XAML 本身正确解析 pack:// URI。

private BitmapImage _listIcon;
public BitmapImage ListIcon
{
    get
    {
        if (_listIcon == null)
        {
            _listIcon = ProvideListIcon();
        }

        return _listIcon;
    }
}

protected override BitmapImage ProvideListIcon()
{
    BitmapImage img = new BitmapImage(new Uri("pack://application:,,,/[Project];Component/Images/TestImage.png", UriKind.RelativeOrAbsolute));
    if (img.CanFreeze)
    {
        img.Freeze();
    }

    return img;
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-05-26
    • 2021-06-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-09-07
    相关资源
    最近更新 更多