Подскажите, как можно получить все кнопки из формы wpf и загнать их в массив?
1 ответ
using System.Collections.Generic;
using System.Windows;
using System.Windows.Media;
...
public static List<T> GetVisualChilds<T>(DependencyObject parent) where T : DependencyObject
{
List<T> childs = new List<T>();
int numVisuals = VisualTreeHelper.GetChildrenCount(parent);
for (int i = 0; i < numVisuals; i++)
{
DependencyObject v = VisualTreeHelper.GetChild(parent, i);
if (v is T)
childs.Add(v as T);
childs.AddRange(GetVisualChilds<T>(v));
}
return childs;
}
...
//Естественно this - это Ваша форма или контрол для поиска
List<Button> allButtons = GetVisualChilds<Button>(this.Content as DependencyObject);
-
-
Кнопки добавлены как
<button/>
? Вы точно выполняете код после добавления кнопок на форму? 24 июн 2016 в 11:08 -
<Button x:Name="Add_SettingsPC" Content="Add" HorizontalAlignment="Left" Margin="147,67,0,0" VerticalAlignment="Top" Width="75" Click="Add_SettingsPC_Click"/> Код выполняю после загрузки формы– FastTI24 июн 2016 в 11:40
-
Да, согласен, необходим
GetVisualChilds<Button>(this.Content as DependencyObject)
25 июн 2016 в 10:29