wpf DataGrid滚动鼠标单击滚动滚动行拖放时出错

时间:2017-04-07 08:22:17

标签: wpf datagrid drag

我在DataGrid中编写了DoDragDrop。

但是,我无法点击并拖动DataGrid上的滚动条,因为发生了拖动错误。

但我可以用鼠标滚轮滚动。

我该如何解决?这是我的代码的一部分。

.cs文件

private void datagrid_MouseMove(object sender, MouseEventArgs e)
    {
        if (e.LeftButton == MouseButtonState.Pressed)
        {
            Point currentPosition = e.GetPosition(incidentList);
            object selectedItem = datagrid.SelectedItem;
            if (selectedItem != null)
            {
                DataGridRow container = (DataGridRow)datagrid.ItemContainerGenerator.ContainerFromItem(selectedItem);
                var dataObj = new DataObject();
                dataObj.SetData("DragSource", container);
                if (container != null)
                {

                    DragDrop.DoDragDrop(container, dataObj, DragDropEffects.Copy);
                }
            }
        }            
    }

.xaml文件

<DataGrid x:Name="datagrid" ColumnHeaderStyle="{StaticResource MyColumnHeader}" 
              Style="{DynamicResource DataGridStyle}" CanUserAddRows="False" VerticalAlignment="Stretch"
              Height="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type Grid}}, Path=ActualHeight}"
              HorizontalAlignment="Stretch" MinHeight="150" SelectionMode="Single"
              ItemsSource="{Binding myListData, UpdateSourceTrigger=PropertyChanged}" AutoGenerateColumns="False"            
              SelectedItem="{Binding SelectMyRow}" 
              MouseMove="datagrid_MouseMove"> .....

1 个答案:

答案 0 :(得分:2)

在行上注册处理程序而不是datagrid:

<DataGrid>
    <DataGrid.RowStyle>
        <Style TargetType="DataGridRow">
            <EventSetter Event="MouseMove" Handler="RowMoveHandler"/>
        </Style>
    </DataGrid.RowStyle>

然后将sender-row作为容器:

private void RowMoveHandler(object sender, MouseEventArgs e)
{
    var container = sender as DataGridRow;
    if (container != null && e.LeftButton == MouseButtonState.Pressed)
    {
        var dataObj = new DataObject();
        dataObj.SetData("DragSource", container);
        DragDrop.DoDragDrop(container,
                    dataObj,
                    DragDropEffects.Copy);
    }
}