0

我正在使用这个示例代码:

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显示为 a TextBlock(实际上是TreeViewItem被拖动),并且在这一行:

TreeViewItem container = element as TreeViewItem

即使元素是一个TextBlock. 这是否意味着它不能正确投射?我正在尝试Drag and Drop使用这篇文章来实现。

4

1 回答 1

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));
于 2013-07-01T06:37:11.160 回答