由于PreviewMouseLeftButtonDown,Datagrid内的按钮未被触发
我正在研究WPF应用程序。
根据要求,我想显示数据网格中的项目列表。 每行还有一个“DELETE”按钮,使用此按钮我们可以删除相应的项目。 我还想要Grid的拖放function。 也就是说,用户可以向上/向下移动行。
我正在使用datagrid的“PreviewMouseLeftButtonDown”
和“Drop”
事件来实现拖放function。
对于DELETE按钮,我绑定了删除命令。
Command="{Binding ElementName=viewName,Path=DataContext.DeleteCommand}"
我也试过了
Command="{Binding RelativeSource={RelativeSource Mode=FindAncestor, AncestorType={x:Type DataGrid}}, Path=DataContext.DeleteCommand}"
现在的问题是,当我单击“删除”按钮时,删除命令处理程序不会被触发。 但是,如果我删除数据网格的“PreviewMouseLeftButtonDown”和“Drop”事件,则删除命令处理程序可以正常工作。
另外我注意到,即使在添加PreviewMouseLeftButtonDown事件之后在“PreviewMouseLeftButtonDown”中注释了所有代码,它也会阻止执行Delete命令处理程序。
PreviewMousedown代码
private void dgEmployee_PreviewMouseLeftButtonDown(object sender, MouseButtonEventArgs e) { prevRowIndex = GetDataGridItemCurrentRowIndex(e.GetPosition); if (prevRowIndex < 0) return; dgEmployee.SelectedIndex = prevRowIndex; var selectedEmployee = dgEmployee.Items[prevRowIndex];//as Employee; if (selectedEmployee == null) return; //Now Create a Drag Rectangle with Mouse Drag-Effect //Here you can select the Effect as per your choice DragDropEffects dragdropeffects = DragDropEffects.Move; if (DragDrop.DoDragDrop(dgEmployee, selectedEmployee, dragdropeffects) != DragDropEffects.None) { //Now This Item will be dropped at new location and so the new Selected Item dgEmployee.SelectedItem = selectedEmployee; } // sourceElement.CaptureMouse(); // return; }
我正在努力解决这个问题。
如果有人有解决方案,请告诉我。
谢谢,Ranish
将DragDrop.DoDragDrop
调用移动到datagrid的MouseMove
事件:
private void dgEmployee_MouseMove(object sender, MouseEventArgs e) { if(e.LeftButton == MouseButtonState.Pressed) { Employee selectedEmp = dgEmployee.Items[prevRowIndex] as Employee; if (selectedEmp == null) return; DragDropEffects dragdropeffects = DragDropEffects.Move; if (DragDrop.DoDragDrop(dgEmployee, selectedEmp, dragdropeffects) != DragDropEffects.None) { //Now This Item will be dropped at new location and so the new Selected Item dgEmployee.SelectedItem = selectedEmp; } } }
更新的PreviewMouseLeftButtonDown
处理程序:
void dgEmployee_PreviewMouseLeftButtonDown(object sender, MouseButtonEventArgs e) { prevRowIndex = GetDataGridItemCurrentRowIndex(e.GetPosition); if (prevRowIndex < 0) return; dgEmployee.SelectedIndex = prevRowIndex; }
它不仅可以解决您的问题,还可以提供更好的用户体验。 当我移动鼠标而不是按下行时,应该启动拖动。
下次请链接您正在使用的教程 - 这将使其他人更容易重现您遇到的问题。