【问题标题】:wpf DataGrid Scroll with mouseclick scrollBar Error when Row Drag and Dropwpf DataGrid Scroll with mouseclick scrollBar Error when Row Drag and Drop
【发布时间】:2017-04-07 18:42:33
【问题描述】:

我在 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"> .....

【问题讨论】:

  • 也许您应该验证鼠标位置是否在您的 container 的边界内,甚至更好,在 DataGridRow 而不是 DataGrid 上注册 mousemove,这样您就可以轻松地开始拖动实际拖动行而不是拖动所选项目并干扰滚动条;)

标签: wpf datagrid drag


【解决方案1】:

在行而不是数据网格上注册您的处理程序:

<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);
    }
}

【讨论】:

  • 哇真的谢谢。它有效,我可以用鼠标使用滚动条!但是当我尝试开始拖动一行时, selectedRow 在拖动时会发生变化。为什么会变?
  • @parfum 可能是因为RowMoveHandler 在移动到不同行时开始新的拖动之前没有检查当前活动的拖动操作。
  • 编辑:可能不是这样...您必须提供有关代码的更多详细信息才能得到答案。
猜你喜欢
  • 2019-02-20
  • 2011-10-18
  • 2013-08-13
  • 2020-04-20
  • 1970-01-01
  • 1970-01-01
  • 2022-12-02
  • 2014-11-01
  • 2012-07-16
相关资源
最近更新 更多