0

我正在使用附加属性为 wpf 实现 DragAndDrop-manager。它工作得很好。但问题只有一个。要抓住拖动的项目,我正在使用可视化树。例如,我想要 listboxitem,但 originalsource 是 listboxitem 的边框。所以我只是使用我的一种辅助方法来搜索具有 ListBoxItem 类型的父项。如果我发现我得到它的数据并拖动它。

但我不想让我的 DragAndDrop-manager 仅在使用列表框时可用。不,我想在每个 Itemscontrol 上使用它。但是 DataGrid 使用 DataGridRows,listview 使用 ListViewItem ......那么有没有机会在不一次又一次地编写代码的情况下获取项目?

4

2 回答 2

2

好吧,您可以使用此功能(我更喜欢将其设置为静态):

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

如果你想让我给你一些解释,我一起床就做)

于 2012-07-27T23:35:40.477 回答
0

您可以使用 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**
于 2012-07-27T09:04:05.370 回答