拖动时会丢失WPF Datagrid多项选择

时间:2014-08-02 17:42:11

标签: c# wpf datagrid drag-and-drop

我正在尝试将多个选定的行从一个DataGrid拖到另一个DataGrid。为此,我使用MouseMove事件的处理程序,如下所示:

    private void Distribution_MouseMove(object sender, MouseEventArgs e)
    {
        base.OnMouseMove(e);
        if (e.LeftButton == MouseButtonState.Pressed)
        {
            var dg = sender as DataGrid;
            if (dg == null) return;
            if (dg.SelectedItems.Count == 0) return;

            Point p = e.GetPosition(this);
            HitTestResult result = VisualTreeHelper.HitTest(this, p);
            var obj = result.VisualHit;

            while (VisualTreeHelper.GetParent(obj) != null && !(obj is DataGridRow))
            {
                obj = VisualTreeHelper.GetParent(obj);
            }
            if (obj == null) return;

            var row = obj as DataGridRow;
            if (row == null) return;

            if (dg.SelectedItems.Contains(row.DataContext))
            {
                e.Handled = true;

                DataObject data = new DataObject();
                data.SetData("registries", dg.SelectedItems.Cast<Registry>().ToList());
                DragDrop.DoDragDrop(this, data, DragDropEffects.Move);
            }
        }
    }

问题是,选择多行后,单击拖放会使单击的行成为唯一选定的行,并且只会移动该行。

如何在更改选择之前保留多项选择或我应该使用哪些其他事件来开始拖动?

1 个答案:

答案 0 :(得分:1)

感谢this post,我找到了答案。

首先我添加了一个PreviewMouseLeftButtonDown处理程序,它将所有选定的项添加到另一个列表中:

    private List<Registro> _selected = new List<Registry>();
    private void Distribution_PreviewMouseLeftButtonDown(object sender, MouseButtonEventArgs e)
    {
        var dg = sender as DataGrid;
        if (dg == null) return;
        _selected.Clear();
        _selected.AddRange(dg.SelectedItems.Cast<Registry>());
    }

然后在MouseMove处理程序之后在e.Handled = true;之后和创建DataObject之前添加了以下内容:

                foreach (var registry in _selected)
                {
                    if (!dg.SelectedItems.Contains(registry))
                    {
                        dg.SelectedItems.Add(registry);
                    }
                }

它显示了在网格中取消选择并再次选择的元素,但它按预期工作。