datagrid鼠标双击事件wpf

时间:2018-09-04 11:41:04

标签: c# wpf wpfdatagrid

我已经使用WPF创建了一个应用程序。我已经在数据网格中显示了一些数据。当前,我已使用选择更改事件从数据网格获取数据。我有以下代码

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());
           }
}

仅在用户双击数据网格时才需要获取数据。怎么可能?

2 个答案:

答案 0 :(得分:2)

XAML:

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

后面的代码:

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());
        }
    }
}

P.S。您可以使用空传播来使代码更健壮:

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

答案 1 :(得分:1)

在XAML中:

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

并使用以下代码:

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());
   }
}

希望对您有帮助。