1.GetVisualParent
public static T GetVisualParent<T>(DependencyObject obj) where T : DependencyObject { DependencyObject parent = obj; while (true) { if (parent == null) return null; T t = parent as T; if (t != null) return t; parent = VisualTreeHelper.GetParent(parent); } }
使用示例代码:
Button btn = sender as Button;
ListViewItem item =
Utilities.GetVisualParent<ListViewItem>(btn);
2.GetVisualChildren
1)方法:
public static ReadOnlyCollection<T> GetVisualChildren<T>(DependencyObject obj) where T : DependencyObject { List<T> list = new List<T>(); int count = VisualTreeHelper.GetChildrenCount(obj); for (int i = 0; i < count; i++) { DependencyObject child = VisualTreeHelper.GetChild(obj, i); if (child is T) list.Add((T)child); list.AddRange(GetVisualChildren<T>(child)); } return new ReadOnlyCollection<T>(list); }
2)示例代码 Button btn = sender as Button;
ListViewItem item = Utilities.GetVisualParent<ListViewItem>(btn); if (item == null) return; ReadOnlyCollection<ComboBoxEdit> cbxCollection= Haitai.Common.Utilities.GetVisualChildren<ComboBoxEdit>(item);