Home > database >  How can I remove element if it has a child?
How can I remove element if it has a child?

Time:11-03

I am trying to remove a textblock inside a Border. If I click on a border it works fine but click on a textblock do nothing.

Code: Creation:

Border newBorder = new Border
{
    Height = 50,
    Width = 50,
    BorderBrush = new SolidColorBrush(Colors.Black),
    BorderThickness = new Thickness(2),
    CornerRadius = new CornerRadius(25),
};

TextBlock newTextBlock = new TextBlock  
{
    Background = customColor,
    TextWrapping = TextWrapping.Wrap,
    VerticalAlignment = VerticalAlignment.Center,
    HorizontalAlignment = HorizontalAlignment.Center,
    Text = numberOfNodes.ToString()
};

newBorder.Child = newTextBlock;


CanvasMain.Children.Add(newBorder);

Remove:

if (e.Source is TextBlock)
{
    TextBlock activeTextBlock = (TextBlock)e.OriginalSource;

    if (removeTextBlock == true)
    {
        CanvasMain.Children.Remove(activeTextBlock);
    }
            
}

I did same when it is only a rectangle and there is no problem.

Result: needed a circle with a number inside and it should be removed by a click.

CodePudding user response:

You add the Border to the Children collection of the Canvas and set the TextBlock as the Child of the Border.

So to remove the TextBlock, you should remove it from the Border rather than the Canvas:

private void CanvasMain_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
{
    if (e.Source is TextBlock)
    {
        TextBlock activeTextBlock = (TextBlock)e.OriginalSource;

        if (removeTextBlock == true && activeTextBlock.Parent is Border border)
        {
            border.Child = null;
        }
    }
}
  • Related