I am working on a WPF application.
As per requirement I want to show list of item in data grid. Each row also having a “DELETE” button, using this button we can de
Move the DragDrop.DoDragDrop
call to the datagrid's MouseMove
event:
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;
}
}
}
The updated PreviewMouseLeftButtonDown
handler:
void dgEmployee_PreviewMouseLeftButtonDown(object sender, MouseButtonEventArgs e)
{
prevRowIndex = GetDataGridItemCurrentRowIndex(e.GetPosition);
if (prevRowIndex < 0)
return;
dgEmployee.SelectedIndex = prevRowIndex;
}
Not only does it fix your problem but it provides a better user experience. The drag should be initiated when I move the mouse instead of when I press the row.
Next time please link the tutorial that you are using - it will make it much easier for others to reproduce the issue that you are encountering.