简体   繁体   中英

datagrid mouse double click event wpf

I have created an application using WPF. I have shown some data in the data grid. Currently, I have used selection changed event for getting the data from the data grid. I have following code

private void datagrid1_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            DataGrid dg = sender as DataGrid;
            DataRowView dr = dg.SelectedItem as DataRowView;
            if (dr != null)
            {
                int id = Convert.ToInt32(dr["Id"].ToString());
           }
}

I need to get data only when the user doubles click on the data grid. how is it possible?

XAML:

<DataGrid MouseDown="datagrid1_MouseDown"></DataGrid>

Code behind:

private void datagrid1_MouseDown(object sender, MouseButtonEventArgs e)
{
    if (e.ChangedButton == MouseButton.Left && e.ClickCount == 2)
    {
        DataGrid dg = sender as DataGrid;
        DataRowView dr = dg.SelectedItem as DataRowView;
        if (dr != null)
        {
            int id = Convert.ToInt32(dr["Id"].ToString());
        }
    }
}

PS You can use null propagation to make your code more robust:

var idStr = ((sender as DataGrid)?.SelectedItem as DataRowView)?["Id"]?.ToString();
if (idStr != null)
{
    int id = Convert.ToInt32(idStr);
}

In XAML:

<datagrid name="datagrid1" ... mousedoubleclick="datagrid1_MouseDoubleClick"></datagrid>

And use this code:

private void datagrid1_MouseDoubleClick(object sender, MouseButtonEventArgs e)
{
    DataGrid dg = sender as DataGrid;

   if (dg!= null && dg.SelectedItems != null && dg.SelectedItems.Count == 1)
   {
       DataRowView dr = dg.SelectedItem as DataRowView;
       int id = Convert.ToInt32(dr["Id"].ToString());
   }
}

I hope it helps you.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM