通过静态类更改图像源时出现问题



我在每个项目中都会遇到一个非常烦人的错误:

我有一个类(相同的命名空间(,我在其中存储对图像的引用,如下所示:

public class Res
{
public static BitmapImage A = new BitmapImage(new Uri(@"imagesA.png", UriKind.Relative));
}

当我试图通过将元素的源更改为这些静态引用之一时

xamldefinedimage.Source = Res.A;

它完全没有任何作用。(当然,我将其与相应的调度员一起附上。(

现在,当我这样分配图像源时:

xamldefinedimage.Source = new BitmapImage(new Uri(@"imagesA.png", UriKind.Relative));

它工作得很好。我检查了图像属性(Ressource,Copy on Build->look ok(。

这个问题让我特别抓狂,因为我有一些旧的项目,其中的参考设置工作得很好。我不想使用变通方法,而是使用一个带有静态引用的特殊类来保持代码最小化。我真的很想弄清真相,一劳永逸地理解我在这里错过了什么。这基本上是一个空白项目,还没有做多少工作。这里的问题是什么,第一种方法不起作用的潜在原因是什么?

您的问题是关于静态类,但您没有将Res类定义为静态。

你的代码应该是这样的:

public static class Res
{
public static BitmapImage A = new BitmapImage(new Uri(@"imagesA.png", UriKind.Relative));
}

此外,如果你的图像在应用程序资源中,那么你的类应该是这样的:

public static class Res
{
public static BitmapImage A = new BitmapImage(new Uri(@"pack://application:,,,/Images/A.png"));
}

最新更新