如何在wpf窗口中获取所有控件? [英] How to get all controls in wpf window?
本文介绍了如何在wpf窗口中获取所有控件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如何获取wpf窗口中的所有控件并进行处理?
解决方案
您可以使用此解决方案:
private void HideAllControl()
{
/// 将内容转换为面板
面板mainContainer =(面板) 此 .Content;
/// GetAll UIElement
UIElementCollection element = mainContainer。儿童;
/// 将UIElementCollection转换为List
列表< span class =code-keyword>< FrameworkElement> lstElement = element.Cast< FrameworkElement> ().ToList();
/// 从列表获取所有控制
var lstControl = lstElement.OfType< Control>();
foreach (控制控制 in lstControl)
{
/// 隐藏所有控件
contol.Visibility = System.Windows.Visibility。隐;
}
}
为此目的,这是您需要学习的WPF的特定部分: http://msdn.microsoft.com/en-us/library/ms753391.aspx [ ^ ]。
-SA
这应该可以做到这一点
公共静态IEnumerable < T > FindVisualChildren < T > (DependencyObject depObj)其中T:DependencyObject
{
if(depObj!= null)
{
for(int i = 0; i < Visu alTreeHelper.GetChildrenCount(depObj); i ++)
{
DependencyObject child = < span class =code-keyword> VisualTreeHelper.GetChild(depObj, i);
if (孩子 ! = null && child T)
{
< span class =code-attribute> yield return (T)child;
}
foreach (T childOfChild FindVisualChildren< T > (child))
{
yield return childOfChild;
}
}
}
}
然后你枚举控件之类的所以
foreach(FindVisualChildren中的TextBlock tb < TextBlock > (窗口))
{
//使用tb执行某些操作
}
How to get all controls in wpf window and processing it?
解决方案
You can use this Solution:
private 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; } }
For such purposes, this is the specific part of WPF you need to learn: http://msdn.microsoft.com/en-us/library/ms753391.aspx[^].
—SA
This should do the trick
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; } } } }
then you enumerate over the controls like so
foreach (TextBlock tb in FindVisualChildren<TextBlock>(window)) { // do something with tb here }
这篇关于如何在wpf窗口中获取所有控件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文