清除所有ComboBoxes方法

时间:2015-08-14 11:57:51

标签: c# wpf combobox

我正在尝试创建一个清除窗口中所有ComboBoxes的方法。这是我到目前为止所尝试的:

private void ClearAllComboboxes(ComboBox cmb)
{
    cmb.SelectedIndex = -1;
}

然后我调用下面的方法,但我一次只能插入一个ComboBox来清除。

private void btnClearAll_Click(object sender, RoutedEventArgs e)
{
    ClearAllComboboxes(cmbBarlocks);
}

所以我要做的就是尽可能少地编写所有组合框。有人可以告诉我如何以及最好的方法是什么?谢谢:))

4 个答案:

答案 0 :(得分:1)

我假设你正在使用MVVM,并且你的viewmodel中的每个组合框都有SelectedItem属性。 在viewmodel中,您可以为每个组合框设置SelectedItem = null。 它将清除你的组合框选择。

如果您没有使用MVVM,那么您可以在后面的代码中使用以下代码:

private void ClearAllComboboxes()
    {
        List<ComboBox> comboBoxes = new List<ComboBox>();

        GetLogicalChildCollection<ComboBox>(container, comboBoxes);

        comboBoxes.ForEach(combobox => combobox.SelectedIndex = -1);
    }

    private static void GetLogicalChildCollection<T>(DependencyObject parent,List<T> logicalCollection) where T : DependencyObject
    {

        var children = LogicalTreeHelper.GetChildren(parent);
        foreach (object child in children)
        {
            if (child is DependencyObject)
            {
                DependencyObject depChild = child as DependencyObject;
                if (child is T)
                {
                    logicalCollection.Add(child as T);
                }
                GetLogicalChildCollection(depChild, logicalCollection);
            }
        }
    }

答案 1 :(得分:0)

在你的处理程序中尝试这个,当我遇到与ListBox类似的问题

时它会起作用
void ClearCombos(params ComboxBox[] boxes)
{
foreach(var box in boxes)
box.ItemsSource = null;
}

并将其命名为ClearCombos(x,y,z);其中x,y,z是您要清除的框

答案 2 :(得分:0)

让我假设您的所有comboboxes都在容器内(让它为stackPanel),您可以使用以下代码段将所选索引设置为-1:

  foreach (Control ctrl in stkContainer.Children)
            {
                if (ctrl.GetType() == typeof(ComboBox))
                {
                    ComboBox cbo = ctrl as ComboBox;
                    ClearAllComboboxes(cbo);
                }
            }

如果要清除组合框意味着必须将方法签名重新定义为:

private void ClearAllComboboxes(ComboBox cmb)
{
   cmb.Items.Clear();
}

答案 3 :(得分:0)

protected void btnAll_Click(object sender, EventArgs e)
        {

            ClearInputs(Page.Controls);
        }

        //For Clear All Control Values
        void ClearInputs(ControlCollection ctrls)
        {
         foreach (Control ctrl in ctrls)
            {
               if (ctrl is ComboBox )
                    ((ComboBox )ctrl).ClearSelection();

                ClearInputs(ctrl.Controls);
            }
        }