How to remove a tag / button based on its name? WPF Visual Studio 2015

I try to remove a shortcut and a button based on their name, but unfortunately the possibility of their removal (what I know) happens through Children.Remove, where it accepts only the actual label / button and not their name, I need a name, so how it determines which button X belongs to whom.

Label labels;
Button buttons;
int counter;

private void button_Copy_Click(object sender, RoutedEventArgs e)
    {
        counter++;

        Label lbl = new Label();
        lbl.Content = counter.ToString();
        lbl.HorizontalAlignment = HorizontalAlignment.Center;
        lbl.VerticalAlignment = VerticalAlignment.Center;
        lbl.FontSize = 50;
        lbl.Name = "lbl" + counter;
        labels = lbl;

        Button bt = new Button();
        bt.Content = "X";
        bt.HorizontalAlignment = HorizontalAlignment.Right;
        bt.VerticalAlignment = VerticalAlignment.Top;
        bt.Name = "btn" + counter;
        buttons = bt;

        bt.Click += Button_Click;

        grid.Children.Add(lbl);
        grid.Children.Add(bt);
    }

    private void Button_Click(object sender, EventArgs e)
    {
        grid.Children.Remove(labels.Name = "btn" + counter);
        grid.Children.Remove(buttons);
    }

Grid. Reset (labels .Name = "btn" + counter); wrong, but I hope he talks about how I wanted this to happen.

+4
source share
1 answer

You can first get the child using the LINQ expression Where:

var child = grid.Children.OfType<Control>().Where(x => x.Name == "btn" + counter).First();

And then call Remove:

grid.Children.Remove(child);
+5
source

Source: https://habr.com/ru/post/1626031/


All Articles