WPF Datagrid 拖放问题

标签 wpf drag-and-drop wpfdatagrid

我有一个 WPF Datagrid,我正在实现拖放功能。
数据网格有一个"file"列表,用户可以拖动它们并将文件复制到桌面。
这样做是这样的:

string[] files = new String[myDataGrid.SelectedItems.Count];
int ix = 0;
foreach (object nextSel in myDataGrid.SelectedItems)
{
    files[ix] = ((Song)nextSel).FileLocation;
    ++ix;
}
string dataFormat = DataFormats.FileDrop;
DataObject dataObject = new DataObject(dataFormat, files);
DragDrop.DoDragDrop(this.myDataGrid, dataObject, DragDropEffects.Copy);  

我有两个问题:
1.当我想拖动多个项目时-这是一个问题,因为在我选择了一对并开始单击一个开始拖动后-只有那个被选中而其他项目被取消选择。我尝试了 here 给出的解决方案但由于某种原因它不起作用。
2.我想在复制后将拖动的项目从数据网格中删除。问题是我不知道如何检查文件是否被复制,或者用户是否只是在屏幕上拖动它而不复制它。

我希望你能帮我解决这些问题。
谢谢!

最佳答案

我想这就是你要找的:

将此代码添加到 DataGrid__PreviewMouseLeftButtonDown 事件处理程序:

private void DataGrid_PreviewMouseLeftButtonDown(object sender, MouseButtonEventArgs e)
{
    this.startingPosition = e.GetPosition(null);

    DependencyObject dep = (DependencyObject)e.OriginalSource;

    // iteratively traverse the visual tree until get a row or null
    while ((dep != null) && !(dep is DataGridRow))
    {
        dep = VisualTreeHelper.GetParent(dep);
    }

    //if this is a row (item)
    if (dep is DataGridRow)
    {
        //if the pointed item is already selected do not reselect it, so the previous multi-selection will remain
        if (songListDB.SelectedItems.Contains((dep as DataGridRow).Item))
        {
            // now the drag will drag all selected files
            e.Handled = true;
        }
    }
}

现在拖动不会改变你的选择。

祝你好运!

我用过 article写下我的答案

关于WPF Datagrid 拖放问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7059620/

相关文章:

python - PySide:将文件拖放到 QListWidget 中

jquery - 可拖动可调整大小在 Chrome 中不起作用

WPF 数据网格 : Blank Row Missing

WPF Treeview - 绑定(bind)到具有不同深度和不同样式的集合

WPF 图像工具提示

.net - MVVM 模式存在哪些问题?

javascript - HTML5 Canvas绘画应用如何实现拖拽?

wpf - 将 ObservableCollection<string> 与转换器绑定(bind)

c# - WPF 数据网格单元格为空

WPF 4 数据网格 : Showing & Hiding Columns