在选择组合框期间出现空引用异常

时间:2017-04-26 07:06:35

标签: c# wpf combobox selection

让我解释一下我的情况。我有wpf用户控件,我动态生成组合框。为此,我使用类Control Control,我使用它们的组合框创建组合框,并为每个组合管理选择更改事件。 Everthing工作很棒,直到我尝试在第一个组合框上升起第二个事件。当我尝试清除第二个组合框的项目时,会出现问题。我做debubugg并且我已经检查过的组合框的引用没有问题(childCmB!= null),但之后尝试了这个组合框的清除项目。抛出异常。 我尝试在论坛上找到很多案例,但取得了任何成功,所以我很感激任何建议来解决这个问题。

谢谢

ControlService.class:

 static class ControlService
{
    private static ObservableDictionary<String, System.Windows.UIElement> controls = new ObservableDictionary<String, System.Windows.UIElement>();
    private static Grid expanderContent;

    public static Expander createExpander(String header, String name, String code)
    {
        header = manageControlName(header);
        ExpanderModelView expanderModelView = new ExpanderModelView(name);

        //Recieve template grid
        expanderContent = expanderModelView.getExpanderContent();
        //Add in static collection
        Expander expander = new Expander() { Header = header };
        //Code of provider service
        expander.Uid = code;
        expander.Name = name;

        //Set up handler
        expanderContent.AddHandler(System.Windows.Controls.ComboBox.SelectionChangedEvent, new SelectionChangedEventHandler(cmb_SelectionChanged));
        //Insert data
        expander.Content = expanderContent;

        controls.Add(header, expander);
        return expander;
    }

    public static void cleanUIElementCollection()
    {
        controls.Clear();
    }




    private static string manageControlName(string name)
    {
        int counter = 1;
        if (controls.Count != 0)
        {
            foreach (String value in controls.Keys)
            {
                if (value.Equals(name))
                {
                    if (name.Any(char.IsDigit))
                        name = name.Substring(0, name.IndexOf("("));

                    name = String.Format(name + "({0})", counter);
                    counter++;
                }
            }
        }
        return name;
    }

    private static void cmb_SelectionChanged(object sender, SelectionChangedEventArgs e)

    {
        Grid currentContent = sender as Grid;
        String selectedItemId = ((e.Source as System.Windows.Controls.ComboBox).SelectedItem as ComboBoxItem).Uid;
        IEnumerable<Parameter> childCmBs = DataService.getServiceParametersByParentId((e.Source as System.Windows.Controls.ComboBox).Uid);

        if (childCmBs.Any())
        {
            foreach (Parameter param in childCmBs)
            {
                try
                {

                System.Windows.Controls.ComboBox childCmB = currentContent.FindName(param.Key) as System.Windows.Controls.ComboBox;
                if (childCmB != null)
                {
                    childCmB.Items.Clear();
                    addComboBoxItems(DataService.getChildrenParameterValuesByParentId(selectedItemId), childCmB);
                }
                }
                catch (Exception ex)
                {
                    System.Windows.MessageBox.Show(String.Format("Happen some problem during creating comboboxes: {0}", ex.Message));
                }
            }
        }
    }

    public static void createComboBoxes(IEnumerable<Parameter> parameters, System.Windows.Controls.Panel panel)
    {
        foreach (Parameter parameter in parameters)
        {
            TextBlock cmbLabel = new TextBlock() { Text = parameter.Caption };
            System.Windows.Controls.ComboBox cmb = new System.Windows.Controls.ComboBox() { Name = parameter.Key, Uid = parameter.ID };
            panel.Children.Add(cmbLabel);
            panel.Children.Add(cmb);

            addComboBoxItems(parameter.ParameterValue, cmb);
        }
    }

    public static void addComboBoxItems(IEnumerable<ParameterValue> parameterValues, System.Windows.Controls.ComboBox cmb)
    { 
        foreach (ParameterValue value in parameterValues)
        {
            ComboBoxItem item = new ComboBoxItem()
            {
                Content = value.Caption,
                Uid = value.ID,
                Name = value.Key
            };
            cmb.Items.Add(item);
        }
    }

}

2 个答案:

答案 0 :(得分:2)

我不确定,但我认为问题在于这一行:

String selectedItemId = ((e.Source as System.Windows.Controls.ComboBox).SelectedItem as ComboBoxItem).Uid;

清除组合框的项目时,

e.Source as System.Windows.Controls.ComboBox).SelectedItem as ComboBoxItem) is null

因此,当您尝试获取null项的Uid时,它会抛出异常。

答案 1 :(得分:2)

清除SelectedItem时没有ComboBox

尽管如此,在尝试使用它之前,应始终检查引用是否有效。所以你的方法应该实现如下:

private static void cmb_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
    Grid currentContent = sender as Grid;
    if (currentContent != null)
    {
        ComboBox comboBox = e.Source as ComboBox;
        if (comboBox != null)
        {
            ComboBoxItem selectedItem = comboBox.SelectedItem as ComboBoxItem;
            if (selectedItem != null)
            {
                String selectedItemId = selectedItem.Uid;
                IEnumerable<Parameter> childCmBs = DataService.getServiceParametersByParentId(selectedItemId);
                if (childCmBs != null && childCmBs.Any())
                {
                    foreach (Parameter param in childCmBs)
                    {
                        try
                        {

                            System.Windows.Controls.ComboBox childCmB = currentContent.FindName(param.Key) as System.Windows.Controls.ComboBox;
                            if (childCmB != null)
                            {
                                childCmB.Items.Clear();
                                addComboBoxItems(DataService.getChildrenParameterValuesByParentId(selectedItemId), childCmB);
                            }
                        }
                        catch (Exception ex)
                        {
                            System.Windows.MessageBox.Show(String.Format("Happen some problem during creating comboboxes: {0}", ex.Message));
                        }
                    }
                }
            }
        }
    }
}