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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/9734120/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-09 08:37:58  来源:igfitidea点击:

Cannot set image source in code behind

c#wpfxamlcode-behind

提问by KMC

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. I have all my image files under a folder named "Images" and all the image files are set to Copy always. And Build Actionis set to Resource, as instructed from documentation.

我已遵循所有这些步骤,但无法设置图像。我在 VS2010 中用 WPF C# 编码。我的所有图像文件都位于名为“ Images”的文件夹下,并且所有图像文件都设置为“始终复制”。并生成操作设置为资源,从文档要求。

My code is as follow. I set a dog.pngin XAML and change it to cat.pngin 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 使设置图像如此复杂..w

[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..

它有效,但我看不出这两个代码之间有任何区别。为什么前者不起作用而后者起作用?对我来说他们是一样的..

采纳答案by Marcin

Try following:

尝试以下操作:

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

Default UriKindis Absolute, you should rather use Relativeone.

默认UriKindAbsolute,你应该使用相对的

[EDIT]

[编辑]

Use BeginInitand EndInit:

使用BeginInitEndInit

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