开发者

Getting hold of grid cell and clearing all controls in it

开发者 https://www.devze.com 2023-03-17 16:03 出处:网络
I have a grid with two columns and multiple rows, each cell containing a number of controls. 开发者_StackOverflowAmong these controls I have a button which should, when I press it, delete all the cont

I have a grid with two columns and multiple rows, each cell containing a number of controls. 开发者_StackOverflowAmong these controls I have a button which should, when I press it, delete all the controls in the current grid cell. How can I get the index of the grid cell my button is in and how can I delete all controls in this cell?


Does this work for you? you'll need to add a using statement for 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);
}


using linq and extending the previous answer, notice the ToList() so you can immediately remove the element

//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);
}
0

精彩评论

暂无评论...
验证码 换一张
取 消