gpt4 book ai didi

c# - 如何根据名称删除标签/按钮? WPF Visual Studio 2015

转载 作者:太空狗 更新时间:2023-10-30 01:02:08 27 4
gpt4 key购买 nike

我正在尝试根据名称删除标签和按钮,但不幸的是,删除它们的选项(据我所知)是通过 Children.Remove 它只接受实际标签/按钮本身而不是它们的名称.我需要名称,因为它决定了哪个 X 按钮属于谁。

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.Children.Remove(labels.Name = "btn"+ counter);是不正确的,但希望它能告诉我我希望它如何发生。

最佳答案

您可以先使用 LINQ Where 表达式获取子元素:

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

然后调用删除:

grid.Children.Remove(child);

关于c# - 如何根据名称删除标签/按钮? WPF Visual Studio 2015,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35018165/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com