C# WPF中的行走树视图问题

C# WPF中的行走树视图问题,c#,wpf,C#,Wpf,我正在使用以下示例代码: private TreeViewItem GetNearestContainer(UIElement element) { // Walk up the element tree to the nearest tree view item. TreeViewItem container = element as TreeViewItem; while ((container == null) && (el

我正在使用以下示例代码:

private TreeViewItem GetNearestContainer(UIElement element)
{
        // Walk up the element tree to the nearest tree view item.
        TreeViewItem container = element as TreeViewItem;

        while ((container == null) && (element != null))
        {
            element = VisualTreeHelper.GetParent(element) as UIElement;
            container = element as TreeViewItem;

        }

        return container;
 }
在运行时,
ui元素
显示为一个
TextBlock
(它实际上是一个正在拖动的
treevieItem
),在这一行:

TreeViewItem container = element as TreeViewItem

即使元素是
TextBlock
,容器也总是填充null。这是否意味着它不能正确施放?我正试图用它来实现一个拖放操作。

我想你可以在可视化树中找到包含文本块的TreeViewItem,类似这样的东西

public static class Exensions
{
    /// <summary>
    /// Traverses the visual tree for a <see cref="DependencyObject"/> looking for a parent of a given type.
    /// </summary>
    /// <param name="targetObject">The object who's tree you want to search.</param>
    /// <param name="targetType">The type of parent control you're after</param>
    /// <returns>
    ///     A reference to the parent object or null if none could be found with a matching type.
    /// </returns>
    public static DependencyObject FindParent(this DependencyObject targetObject, Type targetType)
    {
        DependencyObject results = null;

        if (targetObject != null && targetType != null)
        {
            // Start looking form the target objects parent and keep looking until we either hit null
            // which would be the top of the tree or we find an object with the given target type.
            results = VisualTreeHelper.GetParent(targetObject);
            while (results != null && results.GetType() != targetType) results = VisualTreeHelper.GetParent(results);
        }

        return results;
    }
}
TreeViewItem treeViewItem = textBlock.FindParent(typeof(TreeView));