简体   繁体   English

无法在后面的代码中设置图像源

[英]Cannot set image source in code behind

There are numerous questions and answers regarding setting image source in code behind, such as this Setting WPF image source in code. 关于在后面的代码中设置图像源有很多问题和答案,例如在代码中设置WPF图像源。

I have followed all these steps and yet not able to set an image. 我已经遵循了所有这些步骤,但却无法设置图像。 I code in WPF C# in VS2010. 我在VS2010中使用WPF C#进行编码。 I have all my image files under a folder named " Images " and all the image files are set to Copy always . 我将所有图像文件放在名为“ Images ”的文件夹下,所有图像文件都设置为Copy always And Build Action is set to Resource , as instructed from documentation. 按照文档中的说明,“ 构建操作”设置为“ 资源”

My code is as follow. 我的代码如下。 I set a dog.png in XAML and change it to cat.png in code behind. 我在XAML中设置了一个dog.png并将其更改为后面的代码中的cat.png

// 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;

Then I get a empty, blank image of emptiness. 然后我得到一张空虚的空白图像。 I do not understand why .NET makes setting an image so complicated..w 我不明白为什么.NET会让图像设置如此复杂......

[EDIT] [编辑]

So the following works 以下是有效的

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.. 对我来说他们是一样的..

Try following: 试试以下:

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

Default UriKind is Absolute , you should rather use Relative one. 默认UriKind绝对的 ,你应该使用相对的

[EDIT] [编辑]

Use BeginInit and EndInit : 使用BeginInitEndInit

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM