从特定文件加载图像

ThP*_*ThP 1 c# wpf blend

如何将 ImageSource 设置为来自特定文件夹的图像?

我尝试在 Debug 中移动图像并运行以下代码:

image.Source = new BitmapImage(new Uri("kafpodhlato.png"));
Run Code Online (Sandbox Code Playgroud)

但我收到以下错误:

System.dll 中发生类型为“System.UriFormatException”的未处理异常

附加信息:无效的 URI:无法确定 URI 的格式。

编辑:创建一个名为 Resources 的文件夹,将其设置Build actionResource然后使用以下代码解决了我的问题。

image.Source = new BitmapImage(new Uri(@"pack://application:,,,/Resources/panamaxi.png"));
Run Code Online (Sandbox Code Playgroud)

Cle*_*ens 5

这应该有效:

image.Source = new BitmapImage(new Uri("kafpodhlato.png", UriKind.Relative));
Run Code Online (Sandbox Code Playgroud)

但是,您可能希望通过Pack URI从程序集资源加载图像。

将图像文件添加到您的 Visual Studio 项目,例如添加到名为Images. 然后将其设置Build ActionResource,并通过加载

image.Source = new BitmapImage(new Uri("pack://application:,,,/Images/kafpodhlato.png"));
Run Code Online (Sandbox Code Playgroud)