Combobox交互问题

时间:2017-03-29 19:41:02

标签: wpf combobox

我有一个带有三个组合框的wpf用户控件库(cmbBox1,cmbBox2和cmbBox3)。最初是组合框2& 3被禁用。用户首先从cmbBox1中选择项目。根据用户选择,填充cmbBox2和cmbBox3中的项目。我的代码第一次运行正常。但是,当用户更改box1中的选择时,它会中断。这是我的代码:

private void cmbBox1_SelectedIndexChanged(object sender, EventArgs e)
{
    this.cmbBox2.Items.Clear();
    this.cmbBox3.Items.Clear();

    //this.cmbBox2.ItemsSource = new object[] {};
    //this.cmbBox3.ItemsSource = new object[] {};

    string Box1String = cmbBox1.SelectedItem.ToString();

    if (this.cmbBox1.SelectedIndex == 0)
    {
        this.cmbBox2.ItemsSource = new object[] { "Item2_0"};
        this.cmbBox3.ItemsSource = new object[] { "Item3_0"};
    }
    else if (this.cmbBox1.SelectedIndex == 1)
    {
        this.cmbBox2ItemsSource = new object[] { "Item2_1"};
        this.cmbBox3.ItemsSource = new object[] { "Item3_1"};
    }

}

private void cmbBox2_SelectedIndexChanged(object sender, EventArgs e)
{
    string Box2String = cmbBox2.SelectedItem.ToString();

    //Rest of the code//

}

当表单打开时,代码完美运行。现在选择完成后,如果用户返回并更改了combobox1中的选择,则代码崩溃并显示错误:

System.NullReferenceException:'对象引用未设置为对象的实例。'

在Combobox2 SelectionIndexChanged事件的第一行。我认为这是因为当我在combobox1中发生任何变化时,我正在清除Combobox2和combobox3中的项目。所以我尝试评论这些线路,但也没有成功。我目前不知道为什么会发生这种情况,非常感谢任何帮助。

1 个答案:

答案 0 :(得分:0)

我找到了解决问题的解决方案。我所做的是将组合框2&的选择更改事件脱钩。 3选择改变了combobox1事件。之后,我绑定了组合框2& 3我再次将功能分配给选择更改事件。这是有效的代码。

private void cmbBox1_SelectedIndexChanged(object sender, EventArgs e)
{
    //this.cmbBox2.Items.Clear();
    //this.cmbBox3.Items.Clear();

    //this.cmbBox2.ItemsSource = new object[] {};
    //this.cmbBox3.ItemsSource = new object[] {};

    string Box1String = cmbBox1.SelectedItem.ToString();
    this.cmbBox2.SelectionChanged -= new SelectionChangedEventHandler(cmbBox2_SelectedIndexChanged);
    this.cmbBox3.SelectionChanged -= new SelectionChangedEventHandler(cmbBox3_SelectedIndexChanged);

    if (this.cmbBox1.SelectedIndex == 0)
    {
        this.cmbBox2.ItemsSource = new object[] { "Item2_0"};
        this.cmbBox3.ItemsSource = new object[] { "Item3_0"};
    }
    else if (this.cmbBox1.SelectedIndex == 1)
    {
        this.cmbBox2ItemsSource = new object[] { "Item2_1"};
        this.cmbBox3.ItemsSource = new object[] { "Item3_1"};
    }
    this.cmbBox2.SelectionChanged += new SelectionChangedEventHandler(cmbBox2_SelectedIndexChanged);
    this.cmbBox3.SelectionChanged += new SelectionChangedEventHandler(cmbBox3_SelectedIndexChanged);
}

private void cmbBox2_SelectedIndexChanged(object sender, EventArgs e)
{
    string Box2String = cmbBox2.SelectedItem.ToString();

    //Rest of the code//

}

private void cmbBox3_SelectedIndexChanged(object sender, EventArgs e)
{
    string Box3String = cmbBox3.SelectedItem.ToString();

    //Rest of the code//

}