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

时间:2016-03-18 14:49:38

标签: 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;
    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"/>

但申请刚刚结束,我也不会接受任何例外。这段代码有什么问题?

UPD:

试着这样:

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

}

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

1 个答案:

答案 0 :(得分:1)

分配内容时
squareImages[i].Source = ...

您没有显示squareImages的定义位置。似乎squareImages[i]的值为null

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