如何删除 WPF 中的组合框?

How to delete combobox in WPF?

正如上面的问题,我已经从代码隐藏中动态创建了 ComboBox

代码如下(这段代码在BtnAddComboBox_Click里面)

Grid grid = new Grid();
comboBox = new ComboBox();
comboBox.ItemsSource = salesman2;
comboBox.Name = "cbSalesman";

Button button = new Button();
button.Width = 50;
button.Name = "btnDelete";
button.Height = 30;
button.Background = Brushes.Transparent;
button.BorderBrush = Brushes.Transparent;
button.Click += new RoutedEventHandler(btnDeleteCB_Click);


grid.Children.Add(comboBox);
grid.Children.Add(button);

stackPanel.Children.Add(grid);

我的 XAML(蓝色按钮)有一个 Button 名字 AddComboBox。当用户点击按钮时。 New ComboBox 将与旁边名为 btnDeleteDELETE BUTTON 一起添加。所以这意味着每个组合框都有自己的删除按钮。它没有 ComboBox 的最大数量,因此只要用户单击按钮,它就会继续添加新的 ComboBox。

问题出在我单击 btnDelete 时。它将删除所有添加的组合框(我猜是因为它们具有相同的名称)

这是我的删除方法:

private void btnDeleteCB_Click(object sender, RoutedEventArgs e)
{
    StackPanel stackPanel = FindChildControl<StackPanel>(this,"spSalesmanCombobox") as StackPanel;
    stackPanel.Children.Remove(comboBox);
}

我要的是点击btnDelete的时候,只会删除旁边的ComboBox。我怎样才能做到这一点 ?可以吗?

我想删除 ComboBox 本身。不是所选项目/其中的项目。

你可以尝试这样的事情。它将删除 Combobox 和 Button 所在的 Grid。同时保持所有其他不变。 (我无法验证此代码,因为我现在没有 IDE)

    private void btnDeleteCB_Click(object sender, RoutedEventArgs e)
    {
        Grid grd = (sender as Button).Parent as Grid; //sender is button -> Parent is your grid
        stackPanel.Children.Remove(grd);  //remove that grid from the Stackpanel that contans them all
    }

一般来说,我想提一下 WPF 设计为与 MVVM 一起使用,您不必像这样操作 gui。它比 Windows 使用代码隐藏的形式更难学习,但会在一段时间后得到回报