Remove Specific Type of Children from Grid Control
I want to remove a suppose control whose type is of border, from the grid control. how can I achieve it in WPF C# ?
Sorry Guys, My problem is that I have grid control which has GUI design at XAML end and user con开发者_如何学Ctrol which are added using C# and the some controls are overlapped. Some controls are removed but some are left which overlap one another. How can I remove all controls. The code you have posted work for control which are not overlapped but for overlapped ones, it didn't work.
Here is my code:
int intTotalChildren = grdGrid.Children.Count-1;
for (int intCounter = intTotalChildren; intCounter > 0; intCounter--)
{
if (grdGrid.Children[intCounter].GetType() == typeof(Border))
{
Border ucCurrentChild = (Border)grdGrid.Children[intCounter];
grdGrid.Children.Remove(ucCurrentChild);
}
}
My error was that each time I used the Children.Count
in the for
loop and every time I removed a child, the Children.Count
changed and not all children were removed.
Well, you could walk the VisualTree
and remove anything whose type is of Border
.
static public void RemoveVisual(Visual myVisual)
{
for (int i = 0; i < VisualTreeHelper.GetChildrenCount(myVisual); i++)
{
Visual childVisual = (Visual)VisualTreeHelper.GetChild(myVisual, i);
if(childVisual.GetType() == typeof(Border))
{
// Remove Child
}
// Enumerate children of the child visual object.
RemoveVisual(childVisual);
}
}
The removal I leave up to you, but the above should find all controls within a visual of the type Border
.
try this , grd is the Grid Contol
<Grid x:Name="grd">
<Border x:Name="test1" Margin="5"
Background="red"
BorderBrush="Black"
BorderThickness="5"></Border>
<Button VerticalAlignment="Bottom" Content="Hello" Click="test"></Button>
</Grid>
for(int i=0; i< VisualTreeHelper.GetChildrenCount(grd);i++){
Visual childVisual = (Visual)VisualTreeHelper.GetChild(grd, i);
if (childVisual is Border)
{
grd.Children.Remove((UIElement) childVisual);
}
This is my solution for remove ALL border controls in a grid children collection
int indice = 0;
int childrens = TargetGrid.Children.Count;
for (int i = 0; i < childrens; i++)
{
Border brd = TargetGrid.Children[indice] as Border;
if (brd != null)
{
//Remove children
TargetGrid.Children.RemoveAt(indice);
}
else
{
indice++;
}
}
精彩评论