WPF应用在尝试查找静态资源时关闭

3

这个页面上有一些Image组件和App.xamp中定义的一些静态图片。在启动时,我需要使用随机静态图片来填充Image组件。

int[] squareImageSources = new int[13]; 
Random rnd = new Random();
Image[] squareImages = new Image[13];

public Page1()
{
    squareImages[0] = i0;
    squareImages[1] = i1;
    squareImages[2] = i2;
    squareImages[3] = i3;
    squareImages[4] = i4;
    squareImages[5] = i5;
    squareImages[6] = i6;
    squareImages[7] = i7;
    squareImages[8] = i8;
    squareImages[9] = i9;
    squareImages[10] = i10;
    squareImages[11] = i11;
    squareImages[12] = i12;
    InitializeComponent();
}

private void UserControl_Loaded(object sender, RoutedEventArgs e)
{
    int randomNumber = rnd.Next(28);
    for (int i = 0; i < 13; i++)
    {
        while (squareImageSources.Contains(randomNumber))
            randomNumber = rnd.Next(28);
        squareImageSources[i] = randomNumber;
        squareImages[i].Source = (BitmapImage)System.Windows.Application.Current.FindResource("s" + Convert.ToString(randomNumber + 1)); //application closes here
    }
}

App.xaml:

<BitmapImage x:Key="s1" UriSource="pack://application:,,,/Resources/Photos/1.png"/>
<BitmapImage x:Key="s2" UriSource="pack://application:,,,/Resources/Photos/2.png"/>
.....................................................
<BitmapImage x:Key="s28" UriSource="pack://application:,,,/Resources/Photos/28.jpg"/>

应用程序突然关闭,我没有收到任何异常信息。这段代码有什么问题?

更新:

尝试了以下方法:

try
{
    BitmapImage bi = (BitmapImage)System.Windows.Application.Current.TryFindResource("s" + Convert.ToString(randomNumber + 1));
    squareImages[i].Source = bi; //nullReferenceException
}
catch
{

}

catch捕获NullReferenceException异常。这怎么可能呢?我可以在设计器中使用此资源,它可以正常工作。


你是否在Debug->Exceptions中启用了Common Language Runtime Exceptions?此外,考虑通过配置文件启用WPF跟踪(右键单击并选择配置可能会启动向导 - 对于WCF也是如此)。它提供了我不知道如何获取的详细信息。 - hlintrup
1
你在那一行做了很多事情。你尝试过将该行分开,以验证FindResource调用是否有问题吗?在这样做之后,您可以尝试捕获异常(例如在此处https://msdn.microsoft.com/en-us/library/system.windows.application.findresource(v=vs.110).aspx),然后在此处发布结果。 - Florian
更新了问题 - AndrewR
FindResource 可能会抛出 ResourceReferenceKeyNotFoundException。你没有处理它。如果你也不处理 未处理异常,那么应用程序将崩溃。至于 TryFindResource,它可能会返回 nullsquareImages[i] 不是 Image(而是 null),所以你会得到 NullReferenceException - Sinatr
FindResource()Resources[]返回的结果完全相同。 - AndrewR
1个回答

1
当你将某物分配给
squareImages[i].Source = ...

您没有展示squareImages的定义位置。而且squareImages[i]的值似乎为null
这将在两种情况下抛出NullReferenceException(在第一种情况下将导致应用程序崩溃)。

不,那绝对不是问题。squareImages已经被初始化了。我已经将初始化添加到问题中了。 - AndrewR
这就是问题所在。只需设置一个断点。Page1,然后突然UserControl_Loaded很可疑。 - Sinatr
谢谢!我已经将 squareImages[0] = i0;... 放在了 InitializeComponent(); 之前,而不是之后。我忘记了 InitializeComponent(); 会初始化 i0。 - AndrewR

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接