0

我将我的 TreeViewItem 定制为StackPanelwithimagetextblockinside;我想得到TextBlock内部的参考。因为下面的代码node是类型的TreeviewItem,我相信childrenCound =3它可能是StackPanel image textblock!但它在里面找不到任何TextBlock东西。我从来没有看到任何控制台输出和object _itemToMove返回null

TreeViewItem node = UIHelper.FindVisualParent<TreeViewItem>(e.OriginalSource as FrameworkElement);
var child = VisualTreeHelper.GetChild(node, 0);
int childrenCount = VisualTreeHelper.GetChildrenCount(child);
for (int i = 0; i < childrenCount; i++)
{
    TextBlock vc = VisualTreeHelper.GetChild(child, i) as TextBlock;
    if (vc != null)
    {
        Console.WriteLine("ggggggggggggggggggggggggggggggggggggggggggggggg");

        _itemToMove = vc.Text as object;
    }

}
Console.WriteLine(childrenCount+";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;");
4

2 回答 2

1

可能你的 TextBlock 比你想象的更深。我一直使用以下帮助程序取得成功,该帮助程序足够通用,可以在应用程序的其他地方使用。

public static T FindVisualChild<T>(DependencyObject obj) where T : DependencyObject
{
    if (obj != null)
    {
        for (int i = 0; i < VisualTreeHelper.GetChildrenCount(obj); i++)
        {
            var child = VisualTreeHelper.GetChild(obj, i);
            if (child is T)
            {
               return (T)child;
            }

            T childItem = FindVisualChild<T>(child);
            if (childItem != null) return childItem;
        }
    }
    return null;
}

我想我是从 StackOverflow 的一个类似问题中得到的。

于 2014-11-09T12:37:31.710 回答
-1

正如 Michael T 所说,TreeViewItem 也是 TreeViewItem 的子项。我遇到了这个老问题,因为我只想要单个 TreeViewItem 的 visualtree 元素,而我多次使用的FindVisualChild函数这次没用了。所以我修改了这个函数来检索 TreeVieItem 的元素,不包括里面的 TreeViewItems。该函数基于任何层次结构都由节点定义的事实,并假设节点具有不是子节点类型的 NodeType。但是,您可以在树中深入任意多个级别(HierachyLevels 参数)。该函数还搜索元素的特定类型和名称。

 Public Sub FindChildGroup(Of T As DependencyObject, H As DependencyObject)(Parent As DependencyObject _
     , ChildName As String _
     , ByRef OutputList As List(Of T) _
     , Optional HierachyLevels As Integer = 0)

  Dim childrenCount As Integer = VisualTreeHelper.GetChildrenCount(Parent)

  For i As Integer = 0 To childrenCount - 1

     'Analyze child
     Dim child = VisualTreeHelper.GetChild(Parent, i)

     'Is node?
     Dim IsNode = TypeOf child Is H

     If IsNode And HierachyLevels > 0 Or TypeOf child IsNot H Then

        Dim child_Test As T = TryCast(child, T)

        If child_Test IsNot Nothing Then

           'should be included in the list?
           Dim child_Element As FrameworkElement = TryCast(child_Test, FrameworkElement)

           If child_Element.Name Like ChildName Then
              OutputList.Add(child_Test)
           End If

        End If

        'Go down next level
        If TypeOf child Is H Then HierachyLevels -= 1
        FindChildGroup(Of T, H)(child, ChildName, OutputList, HierachyLevels)
        If TypeOf child Is H Then HierachyLevels += 1

     End If
  Next

结束子

于 2021-01-02T21:17:33.643 回答