简体   繁体   中英

How to find the row value of the cell clicked in a DataGrid on WPF?

http://i.stack.imgur.com/zllpr.png

I wish to click on the end row of this data grid (in the above picture). When clicking this, I want to be able to find which row was clicked and pass the row-number over to another form.

Here are a few attempts that I have tried:

  private void CellClicked(object sender, MouseButtonEventArgs e)
    {
        int cell = dgFake.Items.IndexOf(((DataRowView)dgFake.Items[5]).Row);

        xamlAllocteAudits window = new xamlAllocteAudits
        {
            DataContext = cell
        };
        window.Show();

This attempt stayed as a value of '-1' no matter where I clicked in the column.

private void CellClicked(object sender, MouseButtonEventArgs e)
    {
        int cell = dgFake.Items.IndexOf(dgFake.SelectedIndex);

        xamlAllocteAudits window = new xamlAllocteAudits
        {
            DataContext = cell
        };
        window.Show();

This attempt displayed a different number starting at '-1' and incremented every time I clicked a cell in the column, but even if I click the bottom cell, the first click would always be '-1', so I assume this was not the row number value.

Ben看一下代码 ,该代码通过简单的导航到父级的技巧告诉您一种机制来检测已单击的列,单元格和行。

类似的问题已经在这里回答了看看。

You can use the SelectionChanged event to do that:

private void dataGrid_SelectionChanged(object sender, EventArgs e) 
{
    foreach (var row in dataGrid.SelectedItems) 
    {
        int index = dataGrid.Items.IndexOf(row);
    }
}

If you are using single row selection, then you can just do this:

private void dataGrid_SelectionChanged(object sender, EventArgs e) 
{
    int index = dataGrid.SelectedIndex;
}

If you just want cell data, then you can do this:

private void dataGrid_SelectionChanged(object sender, EventArgs e) 
{
    foreach (DataGridCellInfo cell in dataGrid.SelectedCells) 
    {
        // do something with cell
    }
}

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