0

我在这里完全没有想法

问题是我使用两个组合框,我想从两个组合框中获取值以在 wpf 中的 DataGrid 中显示内容。

我有这个函数可以从两个组合框中获取值。这很好用。

private void cboxYearChange(object sender, SelectionChangedEventArgs e)
    {
        ComboBoxItem typeItemYear = (ComboBoxItem)comboBox2.SelectedItem;
        string valueYear = typeItemYear.Content.ToString();

        ComboBoxItem typeItemMonth = (ComboBoxItem)comboBox1.SelectedItem;
        string valueMonth = typeItemMonth.Content.ToString();
}

但后来我想创建另一个函数来检查另一个组合框的更改:

private void cboxMonthChange(object sender, SelectionChangedEventArgs e)
    {
        ComboBoxItem typeItemYear = (ComboBoxItem)comboBox2.SelectedItem;
        string valueYear = typeItemYear.Content.ToString();

        ComboBoxItem typeItemMonth = (ComboBoxItem)comboBox1.SelectedItem;
        string valueMonth = typeItemMonth.Content.ToString();

} 

我可以构建,但是当我运行它时,我得到 Object reference not set to an instance on the ComboBoxItem typeItemYear = (ComboBoxItem)comboBox2.SelectedItem; cboxMonthChange 函数中的行

我在这里想念什么?

4

2 回答 2

0

SelectedItem 在选择某项之前为空。除非它们同时更改(这是不可能的,因为这些事件是按顺序触发的),comboBox1.SelectedItem 或 comboBox2.SelectedItem 上的类型转换都会引发异常。

检查 SelectedItem 是否设置了方法。或使用其他演员表,例如:

ComboBoxItem item1 = comboBox1.SelectedItem as ComboBoxItem; if (item1 != null) { // 做某事 }

希望这可以帮助 :-)

于 2013-01-01T21:50:47.520 回答
0

1) 尽可能不要在代码中引用控件的名称。
因此,例如,您可以通过将 转换SenderComboBox.
2)但在这种简单的情况下,只需使用公共属性并将它们绑定到您的 ComboBox :所有操作都无需代码即可完成。

<ComboBox x:Name="YearSelectCB" SelectedItem="{Binding SelectedYear}">
<ComboBox x:Name="MonthSelectCB" SelectedItem="{Binding SelectedMonth}">

(您可以通过多种方式设置窗口的 DataContext,例如在窗口加载的事件处理程序 (DataContext=this) 中)

于 2013-01-01T21:56:53.547 回答