2012-07-27 108 views
0

我正在爲使用附加屬性的wpf實現DragAndDrop管理器。它工作得很好。但只有一個問題。要抓取拖動的項目,我使用visualtree。例如我想要有listboxitem,但是originalsource是listboxitem的邊框。所以我只使用我的一個幫助器方法來搜索ListBoxItem類型的父類。如果我發現我得到它的數據並拖動它。WPF在Visualtree中獲取項目控件的項目

,但我不想只是在使用一個列表框有我DragAndDrop經理aviable。不,我想在每個Itemscontrol上使用它。 但是一個DataGrid使用DataGridRows,一個listview使用ListViewItem ...所以有沒有機會獲得該項目,而不再次編寫代碼,一次又一次?

回答

0

好,你可以有這個功能 (我更願意把它當作靜態):

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

,並用它某種這樣的:例如,你想找到yourDependencyObjectToSearchIn容器中的所有文本框元素

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

如果你要我給你提供一些解釋,我會盡快爲我起牀做)

0

您可以使用FrameworkElement或UIElement來識別控件。

控制繼承層次..

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

是的,但是這是沒有用的。這裏的問題是,在視覺樹等elemets也是一個ContentControl中... – 2012-07-27 10:41:23