WPF Get Item of Itemscontrol in Visualtree

梦想与她 提交于 2019-12-11 22:56:03

问题


I am implementing an DragAndDrop-manager for wpf using attached properties. It works quite nice. But there is only one problem. To grab the dragged item i am using the visualtree. As example I want to have the listboxitem but the originalsource is the border of the listboxitem. So I just use one of my helper methods to search for the parent with the type of ListBoxItem. If I found that I get the data of it and drag that.

But I dont want to have my DragAndDrop-manager aviable only while using a listbox. No I want to use it on every Itemscontrol. But a DataGrid uses DataGridRows, a listview uses ListViewItem... So is there any chance to get the item without writing the code again, again and again?


回答1:


well, you can have this function (i prefer to have it as static):

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;
            }
        }
    }
}

and use it some kind of this:
i.e. you want to find all TextBox elements in yourDependencyObjectToSearchIn container

foreach (TextBox txtChild in FindVisualChildren<TextBox>(yourDependencyObjectToSearchIn))
{
    // do whatever you want with child of type you were looking for
    // for example:
    txtChild.IsReadOnly = true;
}

if you want me to provide you some explanation, i'll do this as soon as i get up)




回答2:


You can use FrameworkElement or UIElement to identify the control.

Control inheritance hierarchy..

System.Object

System.Windows.Threading.DispatcherObject

System.Windows.DependencyObject

  System.Windows.Media.Visual
    System.Windows.UIElement
      System.Windows.**FrameworkElement**
        System.Windows.Controls.Control
          System.Windows.Controls.ContentControl
            System.Windows.Controls.ListBoxItem
              System.Windows.Controls.**ListViewItem**

System.Object

System.Windows.Threading.DispatcherObject

System.Windows.DependencyObject

  System.Windows.Media.Visual

    System.Windows.UIElement
      System.Windows.**FrameworkElement**
        System.Windows.Controls.Control
          System.Windows.Controls.**DataGridRow**


来源:https://stackoverflow.com/questions/11684336/wpf-get-item-of-itemscontrol-in-visualtree

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!