我有一个包含两列和多行的网格,每个单元格包含许多控件。在这些控件中,我有一个按钮,当我按下它时,应该删除当前网格单元格中的所有控件。如何获取我的按钮所在的网格单元格的索引以及如何删除此单元格中的所有控件?
答案 0 :(得分:3)
这对你有用吗?您需要为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);
}
答案 1 :(得分:1)
使用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);
}