Florian
Florian

Reputation: 5994

WPF Get Item of Itemscontrol in Visualtree

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?

Upvotes: 0

Views: 2178

Answers (2)

Voronov Alexander
Voronov Alexander

Reputation: 333

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)

Upvotes: 2

Learner
Learner

Reputation: 1542

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**

Upvotes: 0

Related Questions