将按钮从包装面板添加到按钮阵列

将按钮从包装面板添加到按钮阵列

问题描述:

有没有一种方法可以将代码中的按钮从特定的wrapppanel添加到数组或列表中? 我尝试下面的代码,但它不工作:将按钮从包装面板添加到按钮阵列

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(); 

由于PanelChildren属性返回UIElementCollection可能包含任何类型的UIElement的对象,你可以使用OfType LINQ扩展方法只retrive的Button elements:

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