【问题标题】:WPF Application closes while trying to find static resourceWPF 应用程序在尝试查找静态资源时关闭
【发布时间】:2016-07-05 09:17:25
【问题描述】:

我在页面上有一些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。这怎么可能?我可以在设计师中使用这个资源,如果工作正常。

【问题讨论】:

  • 您是否在 Debug->Exceptions 中启用了公共语言运行时异常?此外,考虑通过您的配置文件启用 WPF 跟踪(右键单击并选择配置可能会启动一个向导 - 它适用于 WCF))。它提供了我不知道如何获得的详细信息。
  • 你在这行做了很多。您是否尝试分隔该行以验证 FindResource 调用是否存在问题?完成此操作后,您可以尝试捕获异常(如此处msdn.microsoft.com/en-us/library/…),然后将结果发布在此处。
  • 更新了问题
  • FindResource 可能会抛出 ResourceReferenceKeyNotFoundException。你没有处理它。如果您不处理unhandled exceptions,那么应用程序将简单地崩溃。至于TryFindResource,它可能会返回null。你得到NullReferenceException,因为squareImages[i]不是Image(而是null)。
  • FindResource()Resorces[] 给出完全相同的结果

标签: c# wpf


【解决方案1】:

当你分配东西时

squareImages[i].Source = ...

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

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

【讨论】:

  • 不,这绝对不是问题。 squareImages 已初始化。为问题添加了初始化。
  • 的问题。只需设置一个断点。 Page1 然后突然UserControl_Loaded 很可疑。
  • 谢谢!我将squareImages[0] = i0;... 放在InitializeComponent(); 之前,而不是之后。我忘了 InitializeComponent(); 初始化 i0。
猜你喜欢
  • 2011-02-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-12-04
相关资源
最近更新 更多