【问题标题】:Recieving null reference exception when clicking combobox?单击组合框时收到空引用异常?
【发布时间】:2015-03-19 14:55:42
【问题描述】:

我希望在我的组合框中显示一个项目列表,每个项目应该是一个图像,后跟一些文本。我现在将 1 项添加到我的列表中(我之前将其作为 observiablecollection 保存但同样的问题)。

这是我的组合框:

<ComboBox Grid.Row="0" ItemsSource="{Binding CrewComboSource}" SelectedValue="{Binding Crew01S}" Margin="2,0">
    <ComboBox.ItemTemplate>
        <DataTemplate>
            <StackPanel Orientation="Horizontal">
                <Image Source="{Binding Image}" Width="30"/>
                <TextBlock Text="{Binding Name}" FontStyle="Bold"/>
            </StackPanel>
        </DataTemplate>
    </ComboBox.ItemTemplate>
</ComboBox>

我在这里上课:

class CrewCombo
{
    public string Name
    {
        get;
        set;
    }

    public string Image
    {
        get;
        set;
    }
}

在这里初始化东西:

CrewComboSource = new List<CrewCombo>();
CrewCombo tempCrewMember = new CrewCombo();
tempCrewMember.Name = "test";
tempCrewMember.Image = AppDomain.CurrentDomain.BaseDirectory + "Media\\POP\\Wisp.png";
CrewComboSource.Add(tempCrewMember);

使用时图片显示正确:

<Image Grid.Row="1" HorizontalAlignment="Center" Source="{Binding CrewComboSource[0].Image}" Width="30" />

异常信息:

在 PresentationFramework.dll 中发生了“System.Windows.Markup.XamlParseException”类型的第一次机会异常

附加信息:在“System.Windows.Baml2006.TypeConverterMarkupExtension”上提供值引发了异常。

在 PresentationFramework.dll 中发生了“System.Windows.Markup.XamlParseException”类型的第一次机会异常

附加信息:在“System.Windows.Baml2006.TypeConverterMarkupExtension”上提供值引发了异常。

PresentationFramework.dll 中出现“System.NullReferenceException”类型的未处理异常

附加信息:对象引用未设置为对象的实例。

如果我编辑我的 XAML,使得 datatemplate 中的堆栈面板中的图像和文本块不存在,因此它是打开的堆栈面板、注释、注释、结束堆栈面板,那么我不会遇到这个问题(但显然我没有也不会在组合框中得到任何东西)。取消注释文本块或图像会重新引入异常。

【问题讨论】:

  • 你能添加完整的异常文本和堆栈跟踪吗?
  • 已添加。我没有更多信息,因为它的“外部代码”?
  • 您没有将tempCrewMember 添加到您的列表中...
  • 好吧,我认为 op 没有写它.. 但他正在添加,因为他可以看到图像
  • 我能够添加 tempCrewMember,因为图像在其他地方使用的图像标签中完美显示。此外,在查看变量时,它会被添加。公共列表 CrewComboSource { 获取;放; }

标签: c# wpf combobox nullreferenceexception


【解决方案1】:

我不知道是什么修复了它...但是我手动重写了 XAML,一次 1 步,现在可以正常工作了...这很奇怪。我认为我最终得到的 XAML 是相同的???

<ComboBox Grid.Row="0" ItemsSource="{Binding CrewComboSource}" SelectedValue="{Binding Crew01S}" Margin="2,0">
    <ComboBox.ItemTemplate>
        <DataTemplate>
            <StackPanel Orientation="Horizontal">
                <Image Source="{Binding Image}" Width="30"/>
                <TextBlock Text="{Binding Name}" FontWeight="Bold"/>
            </StackPanel>
        </DataTemplate>
    </ComboBox.ItemTemplate>
</ComboBox>

无论如何,它现在可以正常工作了...不知道为什么。 :/ 是否仍然有兴趣了解为什么会发生这种情况?

【讨论】:

  • XAML 是相同的,这不可能修复您的问题。你一定是在别处改变了一些东西。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-08-29
  • 2018-09-13
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多