选择不同节点时,从TreeView中的Drop事件获取TreeViewItem

时间:2015-02-11 17:13:24

标签: c# wpf listbox treeview

我从ListBox拖放到TreeView中,我遇到的问题是我只能看到" IsSelected"在Drop事件下从TreeView发送器返回的节点,这是因为我从TreeViewItem的列表框中选择一个属性并将其拖动到另一个TreeViewItem中。

我希望能有所作为...

我无法从"删除" TreeViewItem,我目前有这些方法但我无法获取TreeViewItem我将ListBoxItem放入。

private void nodeTree_Drop(object sender, DragEventArgs e)
    {

        if (e.Data.GetDataPresent("copyProperty"))
        {
            BasePropertyTypeVM dragged = e.Data.GetData("copyProperty") as BasePropertyTypeVM;

        }
    }

    private void NodeTree_OnDragEnter(object sender, DragEventArgs e)
    {
        if (!e.Data.GetDataPresent("copyProperty") ||
            sender == e.Source)
        {
            e.Effects = DragDropEffects.None;
        }
    }

    private void NodeTree_OnDragOver(object sender, DragEventArgs e)
    {
        TreeViewItem treeViewItem = FindAncestor<TreeViewItem>((DependencyObject) e.OriginalSource);
        if (treeViewItem != null)
        {

            treeViewItem.Background = Brushes.Blue;
        }

    }

    private void NodeTree_OnDragLeave(object sender, DragEventArgs e)
    {
        TreeViewItem treeViewItem = FindAncestor<TreeViewItem>((DependencyObject) e.OriginalSource);
        if (treeViewItem != null)
        {
            treeViewItem.Background = Brushes.White;
        }
    }

谢谢,

萨姆

1 个答案:

答案 0 :(得分:1)

所以我设法做到了这一点。我使用find ancestor方法获取treeviewitem对象,然后使用此对象的头并将其转换为我用于创建树视图的NodeTreeVM对象。

private void nodeTree_Drop(object sender, DragEventArgs e)
    {
        //find the ancestor using the below method, this gets the TreeViewItem Object
        TreeViewItem treeViewItem = FindAncestor<TreeViewItem>((DependencyObject)e.OriginalSource);
        if (treeViewItem != null)
        {
           treeViewItem.Background = Brushes.White;
           //Convert the header into the origional object
           var droppedNode = (TreeNodeVM)treeViewItem.Header;
        }
    }

private static T FindAncestor<T>(DependencyObject current) where T : DependencyObject
    {
        // Search the VisualTree for specified type
        while (current != null)
        {
            if (current is T)
            {
                return (T) current;
            }
            current = VisualTreeHelper.GetParent(current);
        }
        return null;
    }

我希望这也有助于其他人,请评论以获取更多信息:)