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

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

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

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

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

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

[编辑]

以下是有效的

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

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

试试以下:

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

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

[编辑]

使用BeginInitEndInit

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