[英]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
(藍色按鈕)。 當用戶單擊按鈕時。 新組合框將與旁邊的名為btnDelete
的DELETE BUTTON
一起添加。 因此,這意味着每個comboBox都有其自己的刪除按鈕。 它沒有ComboBox
最大數量,因此只要用戶單擊該按鈕,它將繼續添加新的ComboBox。
問題是當我單擊btnDelete
。 它將刪除所有添加的comboBox(因為我猜它具有相同的名稱)
這是我的刪除方法:
private void btnDeleteCB_Click(object sender, RoutedEventArgs e)
{
StackPanel stackPanel = FindChildControl<StackPanel>(this,"spSalesmanCombobox") as StackPanel;
stackPanel.Children.Remove(comboBox);
}
我想要的是單擊btnDelete
,只有旁邊的ComboBox
會被刪除。 我怎樣才能做到這一點 ? 有可能做到嗎?
我想刪除ComboBox
本身。 而不是其中的選定項目。
您可以嘗試這樣。 它將刪除其中包含“組合框”和“按鈕”的網格。同時不影響其他所有網格。 (我無法驗證此代碼,因為我現在沒有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窗體方式更難學習,但過一會兒就會獲得回報
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.