Datagrid DragDrop to group禁用排序

时间:2016-03-18 14:58:39

标签: wpf sorting datagrid columnheader

我有一个WPF Datagrid,我添加了一个功能,可以根据上一篇文章Drag DataGrid Column header and drop onto a label?将列标题拖到列表框中进行分组。我遇到的一个问题是,当调用DoDragDrop函数时,它会禁用Datagrid的单击到排序功能。有没有办法将列标题拖放到组,但仍然可以单击进行排序?

private void DataGridHeader_PreviewMouseMove(object sender, MouseEventArgs e)
{
    if (e.LeftButton == MouseButtonState.Pressed)
    {               
        var header = e.OriginalSource as ContentControl;
        if (header != null)
        {
            DragDrop.DoDragDrop(header, new DataObject(typeof(string), header.Content.ToString()), DragDropEffects.Move);
            e.Handled = true;
        }
    }
}

private void ListBox_Drop(object sender, DragEventArgs e)
{
    if (e.Data.GetDataPresent(typeof(string)))
    {
        var columnName = (string)e.Data.GetData(typeof(string));

        this.GroupedColumns.Add(columnName);

        var sourceView = CollectionViewSource.GetDefaultView(this.DataGrid.ItemsSource);
        sourceView.GroupDescriptions.Add(new PropertyGroupDescription(columnName));
        sourceView.Refresh();

        e.Handled = true;
    }
}

我正在通过XAML挂钩事件

ListBox Name="HeaderListBox" VerticalContentAlignment="Center" ItemsSource="{Binding GroupedColumns}" AllowDrop="True" Margin="5" Drop="ListBox_Drop"

        <DataGrid.ColumnHeaderStyle>
            <Style TargetType="{x:Type DataGridColumnHeader}">                    
                <EventSetter Event="PreviewMouseMove" Handler="DataGridHeader_PreviewMouseMove"/>
            </Style>
        </DataGrid.ColumnHeaderStyle>

1 个答案:

答案 0 :(得分:0)

我能够通过以下方法解决此问题:节省鼠标左键的位置,然后签入鼠标移动处理程序:

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

    public void DataGridHeader_PreviewMouseMove(object sender, System.Windows.Input.MouseEventArgs e)
    {
        Point mousePos = e.GetPosition(null);
        Vector diff = columnDragDropStartPoint - mousePos;

        if (e.LeftButton == MouseButtonState.Pressed &&
            (Math.Abs(diff.X) > SystemParameters.MinimumHorizontalDragDistance ||
            Math.Abs(diff.Y) > SystemParameters.MinimumVerticalDragDistance))
        {
            var header = e.Source as DataGridColumnHeader;
            if (header != null)
            {
                DragDrop.DoDragDrop(header, new DataObject(typeof(string[]), new[] { header.Column.SortMemberPath.ToString(), header.Content.ToString() }), DragDropEffects.Move);
                e.Handled = true;
            }
        }
    }