繁体   English   中英

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

[英]Cannot set image source in 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;

然后我得到一张空虚的空白图像。 我不明白为什么.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;

暂无
暂无

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

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