按類型查找wpf窗口中的所有控件我在找一種方法來找到窗口上的所有控件,例如:找到所有TextBoxes,查找實現(xiàn)特定接口等的所有控件。
3 回答

萬千封印
TA貢獻1891條經(jīng)驗 獲得超3個贊
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; } } }}
foreach (TextBlock tb in FindVisualChildren<TextBlock>(window)){ // do something with tb here}

胡子哥哥
TA貢獻1825條經(jīng)驗 獲得超6個贊
IEnumerable<myType> collection = control.Children.OfType<myType>();

jeck貓
TA貢獻1909條經(jīng)驗 獲得超7個贊
public static IEnumerable<T> FindLogicalChildren<T> ( DependencyObject depObj ) where T : DependencyObject { if( depObj != null ) { foreach( object rawChild in LogicalTreeHelper.GetChildren( depObj ) ){ if( rawChild is DependencyObject ) { DependencyObject child = (DependencyObject)rawChild; if( child is T ) { yield return (T)child; } foreach( T childOfChild in FindLogicalChildren<T>( child ) ) { yield return childOfChild; } } } } }
- 3 回答
- 0 關(guān)注
- 1704 瀏覽
添加回答
舉報
0/150
提交
取消