我在页面上有一些 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。这怎么可能?我可以在设计器中使用这个资源,如果工作正常的话。
最佳答案
当你分配一些东西给
squareImages[i].Source = ...
您没有显示 squareImages
的定义位置。而且 squareImages[i]
的值似乎是 null
。
这将在两种情况下抛出 NullReferenceException
(第一种情况会使应用程序崩溃)。
关于c# - WPF 应用程序在尝试查找静态资源时关闭,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36087419/