我正在写一个WPF。在其中,我使用 MultiColumnComboBox 来选择一些值。看起来像这样。
<ComboBox x:Name="OutputMatrNr" IsTextSearchEnabled="False" IsEditable="True" ItemsSource="{Binding DataSource}" IsDropDownOpen="False" StaysOpenOnEdit="True" KeyUp="OutputMatrNr_KeyUp" DropDownClosed="ComboBoxStudentOnDropDown" KeyDown="ComboBoxStudentOnKeyPress" SelectedItem="{Binding Path=students, Mode=TwoWay}" BorderThickness="2px" BorderBrush="black" Canvas.Left="2px" Canvas.Top="18px" Width="100px">
<ComboBox.ItemTemplate>
<DataTemplate>
<TextBlock Margin="2" Text="{Binding MatrNr}"/>
</DataTemplate>
</ComboBox.ItemTemplate>
<ComboBox.ItemContainerStyle>
<Style TargetType="{x:Type ComboBoxItem}">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate>
<Grid x:Name="gd" TextElement.Foreground="Black">
<Grid.ColumnDefinitions>
<ColumnDefinition/>
<ColumnDefinition/>
<ColumnDefinition/>
</Grid.ColumnDefinitions>
<TextBlock Margin="5" Grid.Column="0" Text="{Binding MatrNr}"/>
<TextBlock Margin="5" Grid.Column="1" Text="{Binding NachName}"/>
<TextBlock Margin="5" Grid.Column="2" Text="{Binding VorName}"/>
</Grid>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
</ComboBox.ItemContainerStyle>
</ComboBox>
这是背后的代码。
protected void ComboBoxStudentOnDropDown(object sender, EventArgs args)
{
if (((Student)OutputMatrNr.SelectedItem).Equals(null)){ // here sometimes the System.NullReferenceException occures
FillStudentFromComboBox(((Student)OutputMatrNr.SelectedItem).MatrNr.ToString()); // I never(!) get here
}
else
{
Console.WriteLine("else");
}
}
protected void ComboBoxStudentOnKeyPress(object sender, KeyEventArgs e)
{
if (e.Key == Key.Enter)
{
FillStudentFromComboBox(OutputMatrNr.Text); //this works every time
}
}
如果在 ComboBox 中写入 MatrNr,我会过滤其中写入的内容。如果您写下完整的 Nr 并按 Enter 键,一切正常。但是如果你点击一个学生,我总是得到 Null 作为回报(以 else 结尾)。此外,我得到一个 System.NullReferenceException,它每隔一段时间就会发生一次,我无法准确地重现该错误。我错过了一些东西,但我无法弄清楚它是什么。