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;
    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/

相关文章:

c# - 使用 Linq 查询区分

c# - 如何在不使用 .NET 中的 WMI 的情况下找到硬盘设备序列号?

c# - 使用不同显示技术在两个 View 中显示数据的 MVVM 的正确实现

c# - 以编程方式创建缓动函数 C#

c# - 带 OR 语句的 DataTrigger

c# - WPF在TabControl的DataTemplate中绑定(bind)不同的UserControl

c# - 表单运行时不显示上下文菜单项

c# - 多次延迟执行与一次检索

c# - 编写单元测试来检查它是否实现了接口(interface)是否有意义?

c# - WPF中是否有 "All Children loaded"事件