简体   繁体   English

如何删除WPF中的组合框?

[英]How to delete combobox in WPF?

As the question ask above, I have create ComboBox dynamically from code behind. 正如上面的问题所问,我已经从后面的代码动态创建了ComboBox

The code as below (this code is inside BtnAddComboBox_Click ) 如下代码(此代码在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);

And I have a Button name AddComboBox at my XAML (the blue button). 我的XAML上有一个Button名称AddComboBox (蓝色按钮)。 when user click on the button. 当用户单击按钮时。 the New ComboBox will be added along with the DELETE BUTTON named btnDelete beside it. 新组合框将与旁边的名为btnDeleteDELETE BUTTON一起添加。 so that's means every comboBox will have its own delete button. 因此,这意味着每个comboBox都有其自己的删除按钮。 it does not have max number of ComboBox so it will keep adding the new ComboBox whenever user click the button. 它没有ComboBox最大数量,因此只要用户单击该按钮,它将继续添加新的ComboBox。

The problem is when I click the btnDelete . 问题是当我单击btnDelete It will delete all the comboBox added (since it have the same name I guess) 它将删除所有添加的comboBox(因为我猜它具有相同的名称)

This is my delete method: 这是我的删除方法:

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

what I want is when I click the btnDelete , only the ComboBox beside it will deleted. 我想要的是单击btnDelete ,只有旁边的ComboBox会被删除。 How can I do that ? 我怎样才能做到这一点 ? Is it possible to do it ? 有可能做到吗?

I want to the delete the ComboBox itself. 我想删除ComboBox本身。 not the selected item / items inside it. 而不是其中的选定项目。

You can try something like this. 您可以尝试这样。 It will delete the Grid in which the Combobox and the Button is in. While leaving all others untouched. 它将删除其中包含“组合框”和“按钮”的网格。同时不影响其他所有网格。 (I couldnt verify this code as i dont have an IDE right now) (我无法验证此代码,因为我现在没有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
    }

Generally i would like to mention that WPF is designt to be used with MVVM where you do not have to manipulate the gui like this. 通常,我想提到WPF专用于MVVM,而您无需像这样操作gui。 Its a little bit harder to learn than the Windows forms way using the codebehind but will payoff after a while 它比使用后面的代码的Windows窗体方式更难学习,但过一会儿就会获得回报

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM