簡體   English   中英

WPF在Visualtree中獲取Items控件

[英]WPF Get Item of Itemscontrol in Visualtree

我正在使用附加屬性為wpf實現DragAndDrop-manager。 效果很好。 但是只有一個問題。 為了抓住被拖動的物品,我正在使用visualtree。 作為示例,我想擁有listboxitem,但原始源是listboxitem的邊框。 因此,我只使用一種幫助方法來搜索具有ListBoxItem類型的父級。 如果我發現它的數據並將其拖動。

但我不想僅在使用列表框時使DragAndDrop-manager可用。 不,我想在每個Itemscontrol上使用它。 但是一個DataGrid使用DataGridRows,一個listview使用ListViewItem ...那么,有沒有機會一次又一次地不編寫代碼來獲得該項?

好吧,您可以擁有此功能(我更喜歡將其設為靜態):

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容器中找到所有TextBox元素

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

如果您想讓我為您提供一些解釋,我將在起床后立即執行)

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

控制繼承層次結構。

系統對象

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.Windows.Threading.DispatcherObject

System.Windows.DependencyObject

  System.Windows.Media.Visual

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM