这个页面上有一些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异常。这怎么可能呢?我可以在设计器中使用此资源,它可以正常工作。
FindResource
可能会抛出ResourceReferenceKeyNotFoundException
。你没有处理它。如果你也不处理未处理异常
,那么应用程序将崩溃。至于TryFindResource
,它可能会返回null
。squareImages[i]
不是Image
(而是null
),所以你会得到NullReferenceException
。 - SinatrFindResource()
和Resources[]
返回的结果完全相同。 - AndrewR