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

KMC*_*KMC 4 c# wpf xaml code-behind

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

我已经遵循了所有这些步骤,但却无法设置图像.我在VS2010中使用WPF C#进行编码.我将所有图像文件放在名为" Images " 的文件夹下,所有图像文件都设置为Copy always.按照文档中的说明," 构建操作"设置为" 资源".

我的代码如下.我在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;
Run Code Online (Sandbox Code Playgroud)

然后我得到一张空虚的空白图像.我不明白为什么.NET会使图像设置如此复杂......

[编辑]

以下是有效的

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

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

Mar*_*cin 11

试试以下:

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

默认UriKind是绝对的,你应该使用相对的.

[编辑]

使用BeginInit和EndInit:

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