Button inside the Datagrid not getting Fired due to PreviewMouseLeftButtonDown

前端 未结 1 898
自闭症患者
自闭症患者 2021-01-20 10:24

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

1条回答
  •  迷失自我
    2021-01-20 10:58

    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.

    0 讨论(0)
提交回复
热议问题