【问题标题】:WPF Get Item of Itemscontrol in VisualtreeWPF在Visualtree中获取Itemscontrol的项目
【发布时间】:2012-07-25 22:15:21
【问题描述】:

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

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

【问题讨论】:

    标签: c# wpf itemscontrol


    【解决方案1】:

    嗯,你可以拥有这个功能 (我更喜欢将其设为静态):

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

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

    【讨论】:

      【解决方案2】:

      您可以使用 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**
      

      【讨论】:

      • 是的,但这没用。这里的问题是可视化树中的其他元素也是 ContentControl...
      猜你喜欢
      • 2020-05-14
      • 2013-08-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-04-13
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多