C# WPF应用程序在尝试查找静态资源时关闭

C# WPF应用程序在尝试查找静态资源时关闭,c#,wpf,C#,Wpf,我在页面上有一些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; squareIm

我在页面上有一些
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
    }
}

catch
捕获NullReferenceException。这怎么可能?我可以在designer中使用此资源,如果工作正常。

当您为

squareImages[i].Source = ...
您不显示定义了
squareImages
的位置。似乎
squareImages[i]
的值是
null


这将在两种情况下抛出
NullReferenceException
(在第一种情况下,将使应用程序崩溃)。

您是否在调试->异常中启用了公共语言运行时异常?此外,考虑通过配置文件启用WPF跟踪(右击并选择以配置可能启动向导-它用于WCF)。它给出了我不知道如何获得的细节。你在这方面做得相当多。您是否尝试分离该行,以验证FindResource调用是否存在问题?完成后,您可以尝试捕获异常(如此处),然后将结果发布到此处。更新后的问题可能会抛出
ResourceReferenceKeyNotFoundException
。你没有处理它。若处理得不好,那个么应用程序就会崩溃。至于
TryFindResource
它可能返回
null
。你得到的是
NullReferenceException
,因为
squareImages[i]
不是
Image
(但是
null
)。
FindResource()
Resorces[]
给出了完全相同的结果不,这绝对不是问题<代码>方形图像已初始化。在问题中添加了初始化。这就是问题所在。只需设置一个断点
Page1
然后突然加载的
UserControl\u
可疑。谢谢!我已经放置了
squareImages[0]=i0
初始化组件()之前,而不是之后。我忘了
初始化组件()初始化i0。
try
{
    BitmapImage bi = (BitmapImage)System.Windows.Application.Current.TryFindResource("s" + Convert.ToString(randomNumber + 1));
    squareImages[i].Source = bi; //nullReferenceException
}
catch
{

}
squareImages[i].Source = ...