无法在代码后台设置图像源

12 浏览
0 Comments

无法在代码后台设置图像源

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

我已经按照所有这些步骤进行了设置,但仍然无法设置图像。我在VS2010中使用WPF C#编码。我所有的图像文件都在一个名为\"Images\"的文件夹下,所有图像文件都设置为始终复制。并且生成操作设置为资源,如文档中所述。

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

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

admin 更改状态以发布 2023年5月23日
0
0 Comments

尝试以下操作:

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

默认的 UriKind 是 Absolute,您应该使用相对的 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;

0