在TreeView和Textbox之间拖放

时间:2013-09-05 11:16:39

标签: c# wpf drag-and-drop

我有一个有两列的网格。左栏是TreeView,右栏是TextBox。现在我希望能够将项目从TreeView拖动到TextBox,并且所选TreeViewItem的标题应该是文本的附加。我在网上搜索了很多“控件之间的拖放”,但所有这些对我来说都不起作用。

我的实际代码是:

private Point startPoint;

    private void tvPreviewLeftMouseDown(object sender, MouseButtonEventArgs e)
    {
        startPoint = e.GetPosition(null);
    }

    private void tvPreviewMouseMove(object sender, MouseEventArgs e)
    {
        if(e.LeftButton == MouseButtonState.Released)
            return;

        Point mousePos = e.GetPosition(null);
        Vector diff = startPoint - mousePos;
        if (e.LeftButton == MouseButtonState.Pressed &&
            Math.Abs(diff.X) > SystemParameters.MinimumHorizontalDragDistance ||
            Math.Abs(diff.Y) > SystemParameters.MinimumVerticalDragDistance)
        {
            TreeView treeView = sender as TreeView;
            TreeViewItem treeViewItem = FindAnchestor<TreeViewItem>((DependencyObject)e.OriginalSource);
            object val = treeView.ItemContainerGenerator.ItemFromContainer(treeViewItem);
            DataObject dragData = new DataObject("myFormat", treeViewItem.Header);
            DragDrop.DoDragDrop(treeViewItem, dragData, DragDropEffects.Move);
        }
    }

    private static T FindAnchestor<T>(DependencyObject current)
        where T : DependencyObject
    {
        do
        {
            if (current is T)
                return (T) current;
            current = VisualTreeHelper.GetParent(current);
        } while (current != null);
        return null;
    }

    private void frtbDrop(object sender, DragEventArgs e)
    {
        if (e.Data.GetDataPresent("myFormat"))
        {
            var val = (string) e.Data.GetData("myFormat");
        }
    }

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

相应的XAML是:

<Grid >
    <Grid.ColumnDefinitions>
        <ColumnDefinition Width="200"/>
        <ColumnDefinition Width="*"/>
    </Grid.ColumnDefinitions>
    <TreeView Grid.Column="0" x:Name="treeview" PreviewMouseLeftButtonDown="tvPreviewLeftMouseDown" PreviewMouseMove="tvPreviewMouseMove"/>
    <TextBox Grid.Column="1" AllowDrop="True" Drop="frtbDrop" DragEnter="frtbDragEnter"/>
</Grid>

如果我调试它, tvPreviewMouseMove 方法可以正常工作。创建DataObject并获取正确的值。但是,堕落和摔跤事件永远不会被解雇。这有什么不对?

2 个答案:

答案 0 :(得分:1)

解决了它。问题是我订阅了DragEnter-和Drop-Event。我将它们更改为PreviewDragEnter和PreviewDrop,现在它可以正常工作

答案 1 :(得分:0)

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