1
我有一個有兩列和多行的網格,每個單元格包含多個控件。在這些控件中,我有一個按鈕,當按下它時,應刪除當前網格單元格中的所有控件。我如何獲得我的按鈕所在的網格單元格的索引以及如何刪除此單元格中的所有控件?獲取網格單元格並清除其中的所有控件
我有一個有兩列和多行的網格,每個單元格包含多個控件。在這些控件中,我有一個按鈕,當按下它時,應刪除當前網格單元格中的所有控件。我如何獲得我的按鈕所在的網格單元格的索引以及如何刪除此單元格中的所有控件?獲取網格單元格並清除其中的所有控件
這是否適合您?你需要添加一個using
聲明System.Linq
//get the row and column of the button that was pressed.
var row = (int)myButton.GetValue(Grid.RowProperty);
var col = (int)myButton.GetValue(Grid.ColumnProperty);
//go through each child in the grid.
foreach (var uiElement in myGrid.Children)
{ //if the row and col match, then delete the item.
if (uiElement.GetValue(Grid.ColumnProperty) == col && uiElement.GetValue(Grid.RowProperty) == row)
myGrid.Children.Remove(uiElement);
}
使用LINQ和擴展以前的答案,注意ToList(),這樣你就可以立即刪除元素
//get the row and column of the button that was pressed.
var row = (int)myButton.GetValue(Grid.RowProperty);
var col = (int)myButton.GetValue(Grid.ColumnProperty);
//go through each child in the grid.
//if the row and col match, then delete the item.
foreach (var uiElement in myGrid.Children.Where(uiElement => (int)uiElement.GetValue(Grid.ColumnProperty) == col && (int)uiElement.GetValue(Grid.RowProperty) == row).ToList())
{
myGrid.Children.Remove(uiElement);
}
不,它不似乎工作。前兩行正在完成他們的工作,但Linq部分,第三行代碼似乎給出了這個問題。如果你可以解釋它的作用,那麼我可以試着找出原因。謝謝! –
對不起,把你的grid.children和foreach中的孩子放在grid.children中,如果它們與你的按鈕在同一行和列中,刪除它。你實際上可能會把它合併成一個聲明。生病更新原始文章 –
是的,您的評論後,這正是我所做的,但它並沒有真正的工作。在它刪除第一個孩子後,在第二個循環中,它在foreach循環中給我一個InvalidOperationException。任何想法?再次感謝! –