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

时间:2012-03-16 08:39:22

标签: c# wpf xaml code-behind

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

我已按照所有这些步骤操作但无法设置图像。我在VS2010中使用WPF C#进行编码。我将所有图像文件放在名为“图像”的文件夹下,所有图像文件都设置为始终复制构建操作设置为资源,如文档中所示。

我的代码如下。我在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;

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

[编辑]

以下作品

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

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

1 个答案:

答案 0 :(得分:11)

请尝试以下操作:

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

默认 UriKind 绝对,您应该使用 Relative

<强> [编辑]

使用 BeginInit EndInit

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