views:

168

answers:

3

I wan to remove 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 control which are added using C# and the some control are overlapped.some controls are removed but some are left wich are come one another . how can I remove all control., the code you have posted work for control which are not overlapped but for overlapped it din't work.

A: 

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.

Kyle Rozendo
can you give some code example ?
Asim Sajjad
@Asim, was doing so as you added the comment, hehe.
Kyle Rozendo
Thanks for your help. But error was in my code. as I have store total number of children of the grid to separate variable. Thanks for you help. my problem solved now.
Asim Sajjad
A: 

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);
}
Kishore Kumar
A: 

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 I used the Children.Count in the for loop and every time I remove child the Children.Count changes and not all childrens are remove.hope that will help to you as well.

Asim Sajjad