C# 查找所有子控件 WPF
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14875042/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Finding ALL child controls WPF
提问by Chrisjan Lodewyks
I would like to find all of the controls within a WPF control. I have had a look at a lot of samples and it seems that they all either require a Name to be passed as parameter or simply do not work.
我想在 WPF 控件中找到所有控件。我看过很多示例,似乎它们都需要将 Name 作为参数传递,或者根本不起作用。
I have existing code but it isn't working properly:
我有现有代码,但无法正常工作:
public static IEnumerable<T> FindVisualChildren<T>(DependencyObject depObj) where T : DependencyObject
{
if (depObj != null)
{
for (int i = 0; i < VisualTreeHelper.GetChildrenCount(depObj); i++)
{
DependencyObject child = VisualTreeHelper.GetChild(depObj, i);
if (child != null && child is T)
{
yield return (T)child;
}
foreach (T childOfChild in FindVisualChildren<T>(child))
{
yield return childOfChild;
}
}
}
}
For instance it will not get a DataGrid
within a TabItem
.
例如,它不会在 aDataGrid
内得到a TabItem
。
Any suggestions?
有什么建议?
采纳答案by Farhad Jabiyev
You can use these.
你可以使用这些。
public static List<T> GetLogicalChildCollection<T>(this DependencyObject parent) where T : DependencyObject
{
List<T> logicalCollection = new List<T>();
GetLogicalChildCollection(parent, logicalCollection);
return logicalCollection;
}
private static void GetLogicalChildCollection<T>(DependencyObject parent, List<T> logicalCollection) where T : DependencyObject
{
IEnumerable children = LogicalTreeHelper.GetChildren(parent);
foreach (object child in children)
{
if (child is DependencyObject)
{
DependencyObject depChild = child as DependencyObject;
if (child is T)
{
logicalCollection.Add(child as T);
}
GetLogicalChildCollection(depChild, logicalCollection);
}
}
}
You can get child button controls in RootGrid f.e like that:
您可以像这样在 RootGrid fe 中获得子按钮控件:
List<Button> button = RootGrid.GetLogicalChildCollection<Button>();
回答by user2996096
You can use this Example:
您可以使用此示例:
public Void HideAllControl()
{
/// casting the content into panel
Panel mainContainer = (Panel)this.Content;
/// GetAll UIElement
UIElementCollection element = mainContainer.Children;
/// casting the UIElementCollection into List
List < FrameworkElement> lstElement = element.Cast<FrameworkElement().ToList();
/// Geting all Control from list
var lstControl = lstElement.OfType<Control>();
foreach (Control contol in lstControl)
{
///Hide all Controls
contol.Visibility = System.Windows.Visibility.Hidden;
}
}