将环绕面板中的按钮添加到按钮数组

Add buttons from a wrap panel to array of buttons

有没有办法在代码中将按钮从特定包装面板添加到数组或列表? 我尝试了下面的代码,但它不起作用:

foreach(Button b in nameOfWrappanel)
{
    list.Add(b);
}

您必须指定 wrappanel.children 才能访问其子项。

foreach (Button b in nameOfWrappanel.Children)
{
    list.Add(b);
}

您可以使用 Linq:

var buttons = myWrapPanel.Children.OfType<Button>().ToList();

由于 Children 属性 of a Panel returns a UIElementCollection 可能包含任何类型的 UIElement 对象,你可以使用 OfType LINQ 扩展方法仅检索 Button 元素:

foreach (Button b in nameOfWrappanel.Children.OfType<Button>())
{
    list.Add(b);
}