无法在代码后面设置图像源 [英] Cannot set image source in code behind

查看:71
本文介绍了无法在代码后面设置图像源的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

关于在后面的代码中设置图像源的问题和答案很多,例如在代码中设置WPF图像源。

There are numerous questions and answers regarding setting image source in code behind, such as this Setting WPF image source in code.

我已经执行了所有这些步骤,但是仍然无法设置图像。我在VS2010中使用WPF C#进行编码。我的所有图像文件都位于名为 图像的文件夹下,并且所有图像文件均设置为始终复制。按照文档说明,构建操作设置为资源

I have followed all these steps and yet not able to set an image. I code in WPF C# in VS2010. I have all my image files under a folder named "Images" and all the image files are set to Copy always. And Build Action is set to Resource, as instructed from documentation.

我的代码如下。我在XAML中设置了 dog.png ,并在后面的代码中将其更改为 cat.png

My code is as follow. I set a dog.png in XAML and change it to cat.png in code behind.

// my XAML
<Image x:Name="imgAnimal" Source="Images/dog.png" />

// my C#
BitmapImage img = new BitmapImage();
img.UriSource = new Uri(@"pack://application:,,,/FooApplication;component/Images/cat.png");
imgAnimal.Source = img;

然后我得到一个空的空白图像。我不明白为什么.NET使设置图像变得如此复杂。.w

Then I get a empty, blank image of emptiness. I do not understand why .NET makes setting an image so complicated..w

因此以下工作

imgAnimal.Source = new BitmapImage(new Uri(@"pack://application:,,,/FooApplication;component/Images/cat.png"));

它可以工作,但是我看不出两个代码之间有什么区别。为什么前者不起作用而后者却起作用?对我来说,它们是相同的。

It works, but I do not see any difference between the two code. Why the earlier doesn't work and the latter does? To me they are the same..

推荐答案

尝试以下操作:

imgAnimal.Source = new BitmapImage(new Uri("/FooApplication;component/Images/cat.png", UriKind.Relative));

默认 UriKind 绝对,您应该宁可使用相对之一。

Default UriKind is Absolute, you should rather use Relative one.

使用 BeginInit EndInit

BitmapImage img = new BitmapImage();
img.BeginInit();
img.UriSource = new Uri(@"pack://application:,,,/FooApplication;component/Images/cat.png");
img.EndInit();
imgAnimal.Source = img;

这篇关于无法在代码后面设置图像源的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆