WPF查找父元素子元素

时间:2022-12-27 23:47:40

原文:WPF查找父元素子元素

/// <summary>
        /// WPF中查找元素的父元素
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="i_dp"></param>
        /// <returns></returns>
        public static T FindParent<T>(DependencyObject i_dp) where T : DependencyObject
        {
            DependencyObject dobj = (DependencyObject)VisualTreeHelper.GetParent(i_dp);
            if (dobj != null)
            {
                if (dobj is T)
                {
                    return (T)dobj;
                }
                else
                {
                    dobj = FindParent<T>(dobj);
                    if (dobj != null && dobj is T)
                    {
                        return (T)dobj;
                    }
                }
            }
            return null;
        }

/// <summary>
        ///WPF查找元素的子元素
        /// </summary>
        /// <typeparam name="childItem"></typeparam>
        /// <param name="obj"></param>
        /// <returns></returns>
        private childItem FindVisualChild<childItem>(DependencyObject obj)
    where childItem : DependencyObject
        {
            for (int i = 0; i < VisualTreeHelper.GetChildrenCount(obj); i++)
            {
                DependencyObject child = VisualTreeHelper.GetChild(obj, i);
                if (child != null && child is childItem)
                    return (childItem)child;
                else
                {
                    childItem childOfChild = FindVisualChild<childItem>(child);
                    if (childOfChild != null)
                        return childOfChild;
                }
            }
            return null;
        }

//测试listView获取焦点后,将符合条件的的项选中

private void listView_GotFocus(object sender, RoutedEventArgs e)
        {
            DependencyObject dobj = e.OriginalSource as DependencyObject;
            if (null != dobj)
            {
                System.Windows.Controls.ListViewItem gvc = FindParent<System.Windows.Controls.ListViewItem>(dobj);
                if (gvc != null)
                {
                    System.Windows.Controls.ListView listView = FindParent<System.Windows.Controls.ListView>(gvc);
                    if (listView != null)
                    {
                        int index = 0;
                        foreach (var lv in listView.ItemsSource)
                        {
                            if ((FTPFile)gvc.DataContext == lv)
                            {
                                listView.SelectedIndex = index;
                                break;
                            }
                            index++;
                        }
                    }

}
            }
        }