BitmapImage未从WPF 4.5中的资源加载

BitmapImage未从WPF 4.5中的资源加载,wpf,uri,bitmapimage,Wpf,Uri,Bitmapimage,我正在Windows 7上的WPF 4.5上构建WPF菜单项的动态列表。 构建它们并让它们显示标题效果很好。 但我无法让他们加载图标。我已经找到了一些关于这个主题的帖子,但是没有一篇能够解决这个问题。 MenuItem图标绑定到的属性在我的最新尝试中按以下方式定义。但我尝试了相对URI、路径等的所有组合 public override Image MenuIcon { get { Image i = new Image();

我正在Windows 7上的WPF 4.5上构建WPF菜单项的动态列表。 构建它们并让它们显示标题效果很好。 但我无法让他们加载图标。我已经找到了一些关于这个主题的帖子,但是没有一篇能够解决这个问题。 MenuItem图标绑定到的属性在我的最新尝试中按以下方式定义。但我尝试了相对URI、路径等的所有组合

    public override Image MenuIcon
    {
        get
        {
            Image i = new Image();
            BitmapImage src = new BitmapImage();
            src.BeginInit();
            src.UriSource = new Uri(@"pack://application:,,,/" 
                    + Assembly.GetExecutingAssembly().GetName().Name 
                    + ";Images/bold.png", UriKind.Absolute); 
            src.CacheOption = BitmapCacheOption.OnLoad;
            src.EndInit();
            i.Source = src;
            return i;
        }
    }
我收到一个异常,说找不到文件。。。
bold.png文件位于Images文件夹中,具有“Resource”生成操作。

我不确定您是否需要相对或绝对URI(不同的API喜欢其中一个或另一个),但以下是两者:

// These two work regardless which loaded assembly the image is in, so long as you
// replace the assembly name with the name of the assembly containing the image.

// Absolute
new Uri("pack://application:,,,/" + Assembly.GetExecutingAssembly().GetName().Name + ";component/Images/bold.png", UriKind.Absolute);

// Relative
new Uri("/" + Assembly.GetExecutingAssembly().GetName().Name + ";component/Images/bold.png", UriKind.Relative);


// These two should also work if in local assembly (only works from within main
// executing assembly, not from within loaded DLLs).

// Absolute
new Uri("pack://application:,,,/Images/bold.png", UriKind.Absolute);

// Relative
new Uri("Images/bold.png", UriKind.Relative);
看起来您只是缺少路径的“组件”部分,以使其与第一个示例匹配


有关更多信息,请参阅。

的确如此!问题是,我绑定到了MenuItem类型的Icon属性,而不是绑定RibbonMenuItem的ImageSource


感谢您为我指明了正确的方向。

我应该添加图片文件夹中的bold.png文件有一个“资源”构建操作,因此包含了该操作。为什么要用这种复杂的方式创建包URI?新的Uri怎么样pack://application:,,,/Images/bold.png“?我以前试过,但我的图标没有显示出来……我再试了一次,它仍然没有显示出来。调试时,我在源的元数据属性上看到以下内容:Metadata'(I.Source)。Metadata'引发了类型为'System.NotSupportedException'System.Windows.Media.ImageMetadata{System.NotSupportedException}的异常。绝对URI和本地程序集不起作用,即不显示图像。相对Uri引发异常…如果Uri有效(当调用src.EndInit()时不会引发异常),那么问题可能会在稍后的代码流中发生。我不知道您是如何构建视图的,但是单独使用一个返回新图像的方法,而不是返回后来分配给现有图像的ImageSource的方法,看起来有点不寻常。最终在视觉树中放置该图像的位置可能会影响其布局和最终渲染图像的方式。有关如何使用图像的更多信息可能有助于追踪问题。