wpf 如何从代码隐藏设置图像资源 URI
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/21022707/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to Set Image Resource URI from Code-Behind
提问by O. R. Mapper
I am trying to embed a PNG graphic into a DLL and load it into an Image
controlas a BitmapImage
. However, WPF keeps throwing an exception saying that the resource cannot be found.
我试图嵌入PNG图形成一个DLL并将其加载到一个Image
控制的BitmapImage
。但是,WPF 不断抛出异常,说找不到资源。
First, some minimal sample code and the steps to reproduce the problem:
首先,一些最小的示例代码和重现问题的步骤:
Create a WPF project named ImageResTestwith an empty main window (you can set the default namespace to
ImageResTest
). The code-behind file of the main window should look like this:using System; using System.Windows; using System.Windows.Controls; namespace ImageResTest { public partial class Window1 : Window { public Window1() { InitializeComponent(); var obj = new MyData.SomeStuff.MyClass(); this.Content = obj.Img; } } }
Create a class library named ImageResTestLib(you can set the default namespace to
ImageResTest
, as above, so everything discussed here is in the same root namespace).- Add references from ImageResTestLibto PresentationCore, PresentationFramework, System.Xamland WindowsBase.
- Add a reference from ImageResTestto ImageResTestLib.
- Inside ImageResTestLib, add the folder hierarchy
MyData/SomeStuff/Resources
. In the
SomeStuff
folder, add the following file MyClass.cs:using System; using System.Windows; using System.Windows.Controls; using System.Windows.Media; using System.Windows.Media.Imaging; namespace ImageResTest.MyData.SomeStuff { public class MyClass { public MyClass() { img = new Image(); { var bmp = new BitmapImage(); bmp.BeginInit(); bmp.UriSource = new Uri(@"/ImageResTestLib;component/MyData/SomeStuff/Resources/Img.png", UriKind.RelativeOrAbsolute); bmp.EndInit(); img.Source = bmp; img.Width = bmp.PixelWidth; } } private Image img; public Image Img { get { return img; } } } }
In the
Resources
folder, add a PNG file namedImg.png
and set its build action to Resource(as suggested, for example, here).
创建一个名为ImageResTest的 WPF 项目,主窗口为空(您可以将默认命名空间设置为
ImageResTest
)。主窗口的代码隐藏文件应如下所示:using System; using System.Windows; using System.Windows.Controls; namespace ImageResTest { public partial class Window1 : Window { public Window1() { InitializeComponent(); var obj = new MyData.SomeStuff.MyClass(); this.Content = obj.Img; } } }
创建一个名为ImageResTestLib 的类库(您可以将默认命名空间设置为
ImageResTest
,如上所述,因此这里讨论的所有内容都在同一个根命名空间中)。- 添加从ImageResTestLib到PresentationCore、PresentationFramework、System.Xaml和WindowsBase 的引用。
- 添加从ImageResTest到ImageResTestLib的引用。
- 在ImageResTestLib 中,添加文件夹层次结构
MyData/SomeStuff/Resources
。 在
SomeStuff
文件夹中,添加以下文件MyClass.cs:using System; using System.Windows; using System.Windows.Controls; using System.Windows.Media; using System.Windows.Media.Imaging; namespace ImageResTest.MyData.SomeStuff { public class MyClass { public MyClass() { img = new Image(); { var bmp = new BitmapImage(); bmp.BeginInit(); bmp.UriSource = new Uri(@"/ImageResTestLib;component/MyData/SomeStuff/Resources/Img.png", UriKind.RelativeOrAbsolute); bmp.EndInit(); img.Source = bmp; img.Width = bmp.PixelWidth; } } private Image img; public Image Img { get { return img; } } } }
在该
Resources
文件夹中,添加一个名为 PNG 文件Img.png
并将其构建操作设置为Resource(如建议的,例如,here)。
So far, so good - launching this application should create a window which instantiates MyClass
and retrieves an Image
created by that MyClass
instance. That image should have been filled with a BitmapImage
whose data was loaded from the graphic included as a resource.
到目前为止,一切都很好 - 启动这个应用程序应该创建一个窗口,该窗口实例化MyClass
并检索Image
由该MyClass
实例创建的对象。该图像应该填充了BitmapImage
其数据是从作为资源包含的图形加载的。
Unfortunately, there seems to be something wrong with the resource URI. The documentation on MSDNhas not helped so far.
不幸的是,资源 URI 似乎有问题。到目前为止,MSDN上的文档没有帮助。
I have tried the following variants of resource URIs:
我尝试了以下资源 URI 变体:
- The form depicted in the code sample above -
/AssemblyName;component/Path/Filename
- was suggested hereand here, but aDirectoryNotFoundException
is thrown, saying that a part of the pathC:\ImageResTestLib;component\MyData\SomeStuff\Resources\Img.png
was not found. pack://application:,,,/MyData/SomeStuff/Resources/Img.png
was suggested here, here, hereand here, but throws anIOException
saying that the resourcemydata/somestuff/resources/img.png
could not be found.pack://application:,,,/ImageResTestLib;component/MyData/SomeStuff/Resources/Img.png
was also suggested here, as well as here, but throws aFileNotFoundException
saying thatImageResTestLib, Culture=neutral
or one of its dependencies was not found.Resources/Img.png
(relative from the code file) was implied hereand here, but throws aDirectoryNotFoundException
saying thatC:\Users\myusername\Documents\Test\DOTNET\WPFTest\ImageResTest\bin\Debug\Resources\Img.png
was not found.MyData/SomeStuff/Resources/Img.png
(relative to the project), also as implied here, behaves analogously to the previous one.
- 上面代码示例中描述的表单
/AssemblyName;component/Path/Filename
- 在这里和这里都被建议,但是DirectoryNotFoundException
抛出 a ,表示C:\ImageResTestLib;component\MyData\SomeStuff\Resources\Img.png
找不到路径的一部分。 pack://application:,,,/MyData/SomeStuff/Resources/Img.png
被建议为here、here、here和here,但抛出了找不到IOException
资源的说法mydata/somestuff/resources/img.png
。pack://application:,,,/ImageResTestLib;component/MyData/SomeStuff/Resources/Img.png
也有人建议here,以及here,但抛出了一个FileNotFoundException
说法,即ImageResTestLib, Culture=neutral
未找到或它的一个依赖项。Resources/Img.png
(相对于代码文件)在此处和此处暗示,但抛出了未找到的DirectoryNotFoundException
说法C:\Users\myusername\Documents\Test\DOTNET\WPFTest\ImageResTest\bin\Debug\Resources\Img.png
。MyData/SomeStuff/Resources/Img.png
(相对于项目),也正如此处所暗示的,其行为与前一个类似。
As none of these would work, I tried the following workaround based on a ResourceDictionary
:
由于这些都不起作用,我尝试了以下基于 a 的解决方法ResourceDictionary
:
- Add a WPF resource dictionary named MyClassResources.xamlin the
SomeStuff
folder. - In that resource dictioanry, add a
BitmapImage
resource with the keyimg
. Change the contents of MyClass.cslike this:
using System; using System.Windows; using System.Windows.Controls; using System.Windows.Media; using System.Windows.Media.Imaging; namespace ImageResTest.MyData.SomeStuff { public class MyClass { public MyClass() { ResourceDictionary dict = new ResourceDictionary(); dict.Source = new Uri("/ImgResTestLib;component/MyData/SomeStuff/MyClassResources.xaml", UriKind.RelativeOrAbsolute); img = new Image(); { var bmp = (BitmapImage)dict["img"]; img.Source = bmp; img.Width = bmp.PixelWidth; } } private Image img; public Image Img { get { return img; } } } }
- 在文件夹中添加名为MyClassResources.xaml的 WPF 资源字典
SomeStuff
。 - 在该资源字典中,添加
BitmapImage
带有键的资源img
。 像这样更改MyClass.cs的内容:
using System; using System.Windows; using System.Windows.Controls; using System.Windows.Media; using System.Windows.Media.Imaging; namespace ImageResTest.MyData.SomeStuff { public class MyClass { public MyClass() { ResourceDictionary dict = new ResourceDictionary(); dict.Source = new Uri("/ImgResTestLib;component/MyData/SomeStuff/MyClassResources.xaml", UriKind.RelativeOrAbsolute); img = new Image(); { var bmp = (BitmapImage)dict["img"]; img.Source = bmp; img.Width = bmp.PixelWidth; } } private Image img; public Image Img { get { return img; } } } }
Now, the resource dictionary can be loaded from the indicated URI (when removing the contents of the resource dictionary, loading completes successfully). However, the PNG graphics are still not found when using a path like /ImageResTestLib;component/MyData/SomeStuff/Resources/Img.png
.
现在,可以从指定的 URI 加载资源字典(删除资源字典的内容时,加载成功完成)。但是,使用类似/ImageResTestLib;component/MyData/SomeStuff/Resources/Img.png
.
What am I doing wrong and how can I load the respective resources (if possible, without the extra resource dictionary)?
我做错了什么,如何加载相应的资源(如果可能,没有额外的资源字典)?
EDIT: Some more information:
编辑:更多信息:
- I am using a German Windows 7 x64
- .NET 4.0 Client is set as the target framework
- Just to make sure, I have tried building and running this both from within Visual Studio 2010 and SharpDevelop 4.3.3; both times resulting in the same exception.
- 我使用的是德语 Windows 7 x64
- .NET 4.0 Client 设置为目标框架
- 只是为了确保,我已经尝试在 Visual Studio 2010 和 SharpDevelop 4.3.3 中构建和运行它;两次都导致相同的异常。
The stacktrace of the FileNotFoundException
I am getting based on Ian's code is as follows:
FileNotFoundException
我根据Ian的代码得到的堆栈跟踪如下:
System.Windows.Markup.XamlParseException: Zeilennummer "3" und Zeilenposition "2" von "Durch den Aufruf des Konstruktors für Typ "ImageResTest.Window1", der den angegebenen Bindungseinschr?nkungen entspricht, wurde eine Ausnahme ausgel?st.". ---> System.IO.FileNotFoundException: Die Datei oder Assembly "ImageResTestLib, Culture=neutral" oder eine Abh?ngigkeit davon wurde nicht gefunden. Das System kann die angegebene Datei nicht finden.
bei System.Reflection.RuntimeAssembly._nLoad(AssemblyName fileName, String codeBase, Evidence assemblySecurity, RuntimeAssembly locationHint, StackCrawlMark& stackMark, IntPtr pPrivHostBinder, Boolean throwOnFileNotFound, Boolean forIntrospection, Boolean suppressSecurityChecks)
bei System.Reflection.RuntimeAssembly.nLoad(AssemblyName fileName, String codeBase, Evidence assemblySecurity, RuntimeAssembly locationHint, StackCrawlMark& stackMark, IntPtr pPrivHostBinder, Boolean throwOnFileNotFound, Boolean forIntrospection, Boolean suppressSecurityChecks)
bei System.Reflection.RuntimeAssembly.InternalLoadAssemblyName(AssemblyName assemblyRef, Evidence assemblySecurity, RuntimeAssembly reqAssembly, StackCrawlMark& stackMark, IntPtr pPrivHostBinder, Boolean throwOnFileNotFound, Boolean forIntrospection, Boolean suppressSecurityChecks)
bei System.Reflection.Assembly.Load(AssemblyName assemblyRef)
bei System.Windows.Navigation.BaseUriHelper.GetLoadedAssembly(String assemblyName, String assemblyVersion, String assemblyKey)
bei MS.Internal.AppModel.ResourceContainer.GetResourceManagerWrapper(Uri uri, String& partName, Boolean& isContentFile)
bei MS.Internal.AppModel.ResourceContainer.GetPartCore(Uri uri)
bei System.IO.Packaging.Package.GetPartHelper(Uri partUri)
bei System.IO.Packaging.Package.GetPart(Uri partUri)
bei System.IO.Packaging.PackWebResponse.CachedResponse.GetResponseStream()
bei System.IO.Packaging.PackWebResponse.GetResponseStream()
bei System.IO.Packaging.PackWebResponse.get_ContentType()
bei System.Windows.Media.Imaging.BitmapDecoder.SetupDecoderFromUriOrStream(Uri uri, Stream stream, BitmapCacheOption cacheOption, Guid& clsId, Boolean& isOriginalWritable, Stream& uriStream, UnmanagedMemoryStream& unmanagedMemoryStream, SafeFileHandle& safeFilehandle)
bei System.Windows.Media.Imaging.BitmapDecoder.CreateFromUriOrStream(Uri baseUri, Uri uri, Stream stream, BitmapCreateOptions createOptions, BitmapCacheOption cacheOption, RequestCachePolicy uriCachePolicy, Boolean insertInDecoderCache)
bei System.Windows.Media.Imaging.BitmapImage.FinalizeCreation()
bei System.Windows.Media.Imaging.BitmapImage.EndInit()
bei ImageResTest.MyData.SomeStuff.MyClass..ctor(Uri baseUri) in C:\Users\username\Documents\Test\DOTNET\WPFTest\ImgResTestLib\MyData\SomeStuff\MyClass.cs:Zeile 36.
bei ImageResTest.Window1..ctor() in c:\Users\username\Documents\Test\DOTNET\WPFTest\ImageResTest\Window1.xaml.cs:Zeile 17.
--- End of inner exception stack trace ---
bei System.Windows.Markup.WpfXamlLoader.Load(XamlReader xamlReader, IXamlObjectWriterFactory writerFactory, Boolean skipJournaledProperties, Object rootObject, XamlObjectWriterSettings settings, Uri baseUri)
bei System.Windows.Markup.WpfXamlLoader.LoadBaml(XamlReader xamlReader, Boolean skipJournaledProperties, Object rootObject, XamlAccessLevel accessLevel, Uri baseUri)
bei System.Windows.Markup.XamlReader.LoadBaml(Stream stream, ParserContext parserContext, Object parent, Boolean closeStream)
bei System.Windows.Application.LoadBamlStreamWithSyncInfo(Stream stream, ParserContext pc)
bei System.Windows.Application.LoadComponent(Uri resourceLocator, Boolean bSkipJournaledProperties)
bei System.Windows.Application.DoStartup()
bei System.Windows.Application.<.ctor>b__1(Object unused)
bei System.Windows.Threading.ExceptionWrapper.InternalRealCall(Delegate callback, Object args, Int32 numArgs)
bei MS.Internal.Threading.ExceptionFilterHelper.TryCatchWhen(Object source, Delegate method, Object args, Int32 numArgs, Delegate catchHandler)
bei System.Windows.Threading.DispatcherOperation.InvokeImpl()
bei System.Windows.Threading.DispatcherOperation.InvokeInSecurityContext(Object state)
bei System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
bei System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
bei System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
bei System.Windows.Threading.DispatcherOperation.Invoke()
bei System.Windows.Threading.Dispatcher.ProcessQueue()
bei System.Windows.Threading.Dispatcher.WndProcHook(IntPtr hwnd, Int32 msg, IntPtr wParam, IntPtr lParam, Boolean& handled)
bei MS.Win32.HwndWrapper.WndProc(IntPtr hwnd, Int32 msg, IntPtr wParam, IntPtr lParam, Boolean& handled)
bei MS.Win32.HwndSubclass.DispatcherCallbackOperation(Object o)
bei System.Windows.Threading.ExceptionWrapper.InternalRealCall(Delegate callback, Object args, Int32 numArgs)
bei MS.Internal.Threading.ExceptionFilterHelper.TryCatchWhen(Object source, Delegate method, Object args, Int32 numArgs, Delegate catchHandler)
bei System.Windows.Threading.Dispatcher.LegacyInvokeImpl(DispatcherPriority priority, TimeSpan timeout, Delegate method, Object args, Int32 numArgs)
bei MS.Win32.HwndSubclass.SubclassWndProc(IntPtr hwnd, Int32 msg, IntPtr wParam, IntPtr lParam)
bei MS.Win32.UnsafeNativeMethods.DispatchMessage(MSG& msg)
bei System.Windows.Threading.Dispatcher.PushFrameImpl(DispatcherFrame frame)
bei System.Windows.Threading.Dispatcher.PushFrame(DispatcherFrame frame)
bei System.Windows.Threading.Dispatcher.Run()
bei System.Windows.Application.RunDispatcher(Object ignore)
bei System.Windows.Application.RunInternal(Window window)
bei System.Windows.Application.Run(Window window)
bei System.Windows.Application.Run()
bei ImageResTest.App.Main() in c:\Users\username\Documents\Test\DOTNET\WPFTest\ImageResTest\obj\Debug\App.g.cs:Zeile 0.
EDIT2:
编辑2:
Adding
添加
Debug.WriteLine(typeof(MyData.SomeStuff.MyClass).Assembly.GetName().FullName);
to the constructor of the main window results in the following output:
到主窗口的构造函数会产生以下输出:
ImgResTestLib, Version=1.0.5123.16826, Culture=neutral, PublicKeyToken=null
The call to
对
Debug.WriteLine(BaseUriHelper.GetBaseUri(this).ToString());
prints the following:
打印以下内容:
pack://application:,,,/ImageResTest;component/window1.xaml
EDIT3:
编辑3:
While the accepted answer solves the problem described by this question, the actual reason for why I could not see my graphic in my actual project was quite something different:
虽然接受的答案解决了这个问题所描述的问题,但我在实际项目中看不到我的图形的实际原因却大不相同:
While neither VS 2010 nor SharpDevelopgive anyindication of that, resources marked as Resourceactually have a logical name (in my case, they retained it from when I had tentatively set the build action to EmbeddedResourceand changed the logical name). The logical name still appears in a <LogicalName>
element in the MSBuild file and from what I can see in ILSpy, thatis what is actually used as the resource name in the compiled assembly.
虽然VS 2010 和 SharpDevelop 都没有给出任何指示,但标记为Resource 的资源实际上有一个逻辑名称(在我的例子中,他们保留了它,因为我暂时将构建操作设置为EmbeddedResource并更改了逻辑名称)。逻辑名称仍然出现在<LogicalName>
MSBuild 文件中的一个元素中,从我在ILSpy 中可以看到,这就是实际用作编译程序集中资源名称的名称。
The correct (working) resource URI to such a resource with a logical nameseems to be
具有逻辑名称的此类资源的正确(工作)资源 URI似乎是
/MyAssembly;component/LogicalResourceName
(thus replacing the directory path to the resource, as usual for EmbeddedResourceresources)
(因此替换资源的目录路径,就像EmbeddedResource资源一样)
While it is not possible to change the logical name in VS or SharpDevelop while the build action is set to Resource, removing the resource and re-adding the file, then setting the build action to Resource, makes the filename-based URIs work again as the logical name will not be in the project file any more. Likewise, removing the <LogicalName>
element manually from the MSBuild file should work.
虽然在构建操作设置为Resource 时无法更改 VS 或 SharpDevelop 中的逻辑名称,但删除资源并重新添加文件,然后将构建操作设置为Resource,使基于文件名的 URI 再次工作逻辑名称将不再出现在项目文件中。同样,<LogicalName>
从 MSBuild 文件中手动删除元素应该可以工作。
回答by Ian Griffiths
Part of the problem is that WPF has no context with which to resolve that URL. It's a relative URL, and typically, it would be resolved relative to the base URI of the XAML content in which it's used. If I use exactly the same URL you start with in this code:
部分问题是 WPF 没有用于解析该 URL 的上下文。它是一个相对 URL,通常会相对于使用它的 XAML 内容的基本 URI 进行解析。如果我使用与您在此代码中开始的完全相同的 URL:
public MainWindow()
{
InitializeComponent();
var img = new Image();
Content = img;
var bmp = new BitmapImage();
bmp.BeginInit();
bmp.UriSource = new Uri(@"/ImageResTestLib;component/MyData/SomeStuff/Resources/Img.png", UriKind.RelativeOrAbsolute);
bmp.EndInit();
img.Source = bmp;
img.Width = bmp.PixelWidth;
}
then it works. That's in the codebehind for MainWindow
, obviously.
那么它的工作原理。MainWindow
显然,这是在代码隐藏中。
With one tiny change, moving this line:
通过一个微小的变化,移动这条线:
Content = img;
to the end, then I get the same DirectoryNotFoundException
as you.
到最后,那我就DirectoryNotFoundException
和你一样了。
WPF tries to resolve that URI to an actual resource at the point at which you assign the BitmapImage
as the Source
property of that Image
. My first example works because the Image
is in the visual tree, and so it picks up the base URI of MainWindow.xaml
, and resolves that resource URI relative to that base URI.
WPF 尝试将该 URI 解析为实际资源,在您将 指定BitmapImage
为 的Source
属性时Image
。我的第一个示例有效,因为Image
位于可视化树中,因此它选取 的基本 URI MainWindow.xaml
,并相对于该基本 URI 解析该资源 URI。
If you really need to create the Image
before it gets associated with a visual tree, you've got various options. You could actually set the base URI on the image:
如果你真的需要Image
在它与可视化树关联之前创建它,你有多种选择。您实际上可以在图像上设置基本 URI:
img.SetValue(BaseUriHelper.BaseUriProperty, baseUri);
However, that's kind of weird. It's easier just to construct an absolute URI, e.g.:
然而,这有点奇怪。构造绝对URI更容易,例如:
bmp.UriSource = new Uri(
baseUri,
@"/ImageResTestLib;component/MyData/SomeStuff/Resources/Img.png");
Both of these of course presume that you know what the base URI is. You can find that out by asking in your MainWindow constructor:
这两个当然都假定您知道基本 URI 是什么。您可以通过在 MainWindow 构造函数中询问来发现这一点:
public MainWindow()
{
InitializeComponent();
var baseUri = BaseUriHelper.GetBaseUri(this);
...
In your case, that'll be: pack://application:,,,/ImageResTest;component/mainwindow.xaml
在你的情况下,那将是: pack://application:,,,/ImageResTest;component/mainwindow.xaml
This in turn makes it clear what the resolved URI should be: pack://application:,,,/ImageResTestLib;component/MyData/SomeStuff/Resources/Img.png
这反过来又明确了解析的 URI 应该是什么: pack://application:,,,/ImageResTestLib;component/MyData/SomeStuff/Resources/Img.png
Interestingly, you say you try that and get an error. Well I'm trying that exact URI, and I'm not getting an error. Just to be clear, here's my modified version of your MyClass
constructor:
有趣的是,你说你尝试这样做并得到一个错误。好吧,我正在尝试那个确切的 URI,但我没有收到错误消息。为了清楚起见,这是我对MyClass
构造函数的修改版本:
public MyClass(Uri baseUri)
{
img = new Image();
var bmp = new BitmapImage();
bmp.BeginInit();
bmp.UriSource = new Uri(baseUri, @"/ImageResTestLib;component/MyData/SomeStuff/Resources/Img.png");
bmp.EndInit();
img.Source = bmp;
img.Width = bmp.PixelWidth;
}
and here's my MainWindow
constructor:
这是我的MainWindow
构造函数:
public MainWindow()
{
InitializeComponent();
var obj = new MyData.SomeStuff.MyClass(BaseUriHelper.GetBaseUri(this));
this.Content = obj.Img;
}
This works for me, having followed your instructions. If I understand you correctly, you're seeing a FileNotFoundException
when you do this. This makes me wonder if your instructions have omitted something. E.g., I'd expect to see this error if ImageResTestLib
was strongly named. (If you want to refer to a resource in a strongly-named library, you need a fully qualified assembly display name before the ;component
part.)
按照您的指示,这对我有用。如果我理解正确,那么您在FileNotFoundException
执行此操作时会看到 a 。这让我怀疑您的说明是否遗漏了某些内容。例如,如果ImageResTestLib
被强命名,我希望看到这个错误。(如果要引用强命名库中的资源,则需要在;component
零件之前使用完全限定的装配显示名称。)
Another option would be to use Application.GetResourceStream
, along with the BitmapImage.StreamSource
property. But again, this is going to need a working URL, so you're likely going to hit the same problem as you had before. Once you work out what's different in your project that's stopping pack://application:,,,/ImageResTestLib;component/MyData/SomeStuff/Resources/Img.png
from working, then the basic approach you already have should be fine.
另一种选择是使用Application.GetResourceStream
,以及BitmapImage.StreamSource
属性。但同样,这将需要一个有效的 URL,因此您可能会遇到与以前相同的问题。一旦你弄清楚你的项目中有什么不同之处停止pack://application:,,,/ImageResTestLib;component/MyData/SomeStuff/Resources/Img.png
工作,那么你已经拥有的基本方法应该没问题。