如何在数据网格中获取单元格值,在 WPF 中的鼠标双击事件中

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18843243/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-13 09:39:53  来源:igfitidea点击:

how to get cellvalue in datagrid, on mouse double click event in WPF

c#wpfdatagridwpfdatagrid

提问by Chhatrapati Sharma

I am new in wpf.

我是 wpf 的新手。

I am binding below datagrid in wpf

我在 wpf 中的 datagrid 下面绑定

<DataGrid AutoGenerateColumns="True" 
          Loaded="dataGrid1_Loaded" 
          MouseDoubleClick="dataGrid1_MouseDoubleClick" 
          Height="350" 
          Width="1200"
          Name="dataGrid1" />

I have one "OID" name column in the grid, and I want to get the value of this column when user double click on row. How can I get it ? which event I should use for it ?

我在网格中有一个“OID”名称列,我想在用户双击行时获取该列的值。我怎么才能得到它 ?我应该使用哪个事件?

I can use view button in datagrid to get column value, but I don't know how to bind buttons/link in datagrid and how to handle it for get column value ?

我可以使用数据网格中的视图按钮来获取列值,但我不知道如何在数据网格中绑定按钮/链接以及如何处理它以获得列值?

Thanks C.P

谢谢CP

回答by Omri Btian

First of all, if you are about to develop a pretty big (over 1 week of development) application you really should start thinking about MVVM.

首先,如果您要开发一个相当大的(超过 1 周的开发)应用程序,您真的应该开始考虑MVVM

In this architecture you wont use event handlers in the code behind. instead, you will use Commandsto send info from your UI to your logic, and Bindingsfrom logic to the UI.

在这种架构中,您不会在后面的代码中使用事件处理程序。相反,您将使用 Commands将信息从 UI 发送到逻辑,以及Bindings从逻辑发送到 UI。

But to answer your current question, you can use the MouseDoubleClickevent and retrieve your data from there

但是要回答您当前的问题,您可以使用该MouseDoubleClick事件并从那里检索您的数据

    private void DataGrid_MouseDoubleClick(object sender, MouseButtonEventArgs e)
    {
        var grid = sender as DataGrid;

        var cellValue = grid.SelectedValue;
    }

This will get the value when the user double clicks the row in the specific column. If you want to get the value of the cell no matter where the user double clicked the row, use:

当用户双击特定列中的行时,这将获得该值。如果您想在用户双击行的任何位置都获取单元格的值,请使用:

grid.SelectedItem

grid.SelectedItem

to get the object that the row represents, and from there retreive your property your column is binded to.

获取该行代表的对象,并从那里检索您的列绑定到的属性。

Hope this helps

希望这可以帮助