在WPF中行走TreeView问题

时间:2013-07-01 03:22:57

标签: 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) && (element != null))
        {
            element = VisualTreeHelper.GetParent(element) as UIElement;
            container = element as TreeViewItem;

        }

        return container;
 }

在运行时,UIElement显示为TextBlock(实际上是TreeViewItem被拖动),并且在此行中:

TreeViewItem container = element as TreeViewItem

即使元素是TextBlock,容器也始终填充null。这是否意味着它无法正确投射?我正在尝试使用此article实现Drag and Drop

1 个答案:

答案 0 :(得分:2)

我猜你可以走可视树来找到包含你的文本块的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));