简体   繁体   中英

Walking TreeView Issue in WPF

I'm using this sample code:

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

At runtime, the UIElement shows up as a TextBlock (it is actually a TreeViewItem being dragged), and on this line:

TreeViewItem container = element as TreeViewItem

The container always gets populated with null even though the element is a TextBlock . Does this mean it cannot be cast properly? I am trying to implement a Drag and Drop using this article .

I guess you could walk the visual tree to find the TreeViewItem that's containing your textblock, something like this.

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

And gets used with the line

TreeViewItem treeViewItem = textBlock.FindParent(typeof(TreeView));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM