单击组合框时接收空引用异常?

时间:2015-03-19 14:55:43

标签: c# wpf combobox nullreferenceexception

我想在我的组合框中显示一个项目列表,每个项目应该是一个图像,后跟一些文本。我现在在我的列表中添加了1个项目(我之前认为它是一个可观察的集合但同样的问题)。

这是我的组合框:

<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中stackpanel中的图像和文本块就不存在了,所以它是打开的stackpanel,comment,comment,end stackpanel然后我没有得到这个问题(但显然我不知道)在组合框中得到任何东西)。取消评论文本块或图像重新引入异常。

1 个答案:

答案 0 :(得分:0)

我不知道是什么修好了......但是我用手重写了XAML,一步一步,它现在工作得很好......很奇怪。我认为我最终得到的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>

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