3

请帮助我,我试图从 SelectionChangedEvent 中的选定行中获取 Cell[0] 的值。

我只是设法获得许多不同的 Microsoft.Windows.Controls,并希望我错过了一些愚蠢的东西。

希望我能从这里得到一些帮助......

    private void datagrid_SelectionChanged(object sender, SelectionChangedEventArgs e)
    {
        Microsoft.Windows.Controls.DataGrid _DataGrid = sender as Microsoft.Windows.Controls.DataGrid;
    }

我希望它会像...

_DataGrid.SelectedCells[0].Value;

但是 .Value 不是一种选择....

非常感谢,这让我发疯了!担

4

5 回答 5

16

更少的代码,它的工作原理。

private void datagrid_SelectionChanged(object sender, SelectionChangedEventArgs e)
    {
        DataGrid dataGrid = sender as DataGrid;
        DataGridRow row = (DataGridRow)dataGrid.ItemContainerGenerator.ContainerFromIndex(dataGrid.SelectedIndex);
        DataGridCell RowColumn = dataGrid.Columns[ColumnIndex].GetCellContent(row).Parent as DataGridCell;
        string CellValue = ((TextBlock)RowColumn.Content).Text;
    }

ColumnIndex 是您想知道的列的索引。

于 2013-09-06T13:41:21.610 回答
9

请检查以下代码是否适合您:

private void dataGrid_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
    DataGrid dataGrid = sender as DataGrid;
    if (e.AddedItems!=null && e.AddedItems.Count>0)
    {
        // find row for the first selected item
        DataGridRow row = (DataGridRow)dataGrid.ItemContainerGenerator.ContainerFromItem(e.AddedItems[0]);
        if (row != null)
        {
            DataGridCellsPresenter presenter = GetVisualChild<DataGridCellsPresenter>(row);
            // find grid cell object for the cell with index 0
            DataGridCell cell = presenter.ItemContainerGenerator.ContainerFromIndex(0) as DataGridCell;
            if (cell != null)
            {
                Console.WriteLine(((TextBlock)cell.Content).Text);
            }
        }
    }
}

static T GetVisualChild<T>(Visual parent) where T : Visual
{
    T child = default(T);
    int numVisuals = VisualTreeHelper.GetChildrenCount(parent);
    for (int i = 0; i < numVisuals; i++)
    {
        Visual v = (Visual)VisualTreeHelper.GetChild(parent, i);
        child = v as T;
        if (child == null) child = GetVisualChild<T>(v);
        if (child != null) break;
    }
    return child;
}

希望这会有所帮助,问候

于 2010-01-28T01:12:53.270 回答
3

这将为您提供 WPF 中 DataGrid 中当前选定的行:-

DataRow dtr = ((System.Data.DataRowView)(DataGrid1.SelectedValue)).Row;

现在要获取单元格值,只需编写dtr[0],dtr["ID"]等。

于 2013-07-21T10:27:12.187 回答
3

由于您使用的是“SelectionChanged”,因此您可以将发件人用作数据网格:

DataGrid dataGrid = sender as DataGrid;
DataRowView rowView = dataGrid.SelectedItem as DataRowView;
string myCellValue = rowView.Row[0].ToString(); /* 1st Column on selected Row */

我尝试了此处发布的答案并且很好,但是在开始隐藏 DataGrid 中的列时给了我问题。即使隐藏列,这个也对我有用。希望它也适合你。

于 2014-04-12T20:18:23.157 回答
1
private void datagrid_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
    DataGrid _DataGrid = sender as DataGrid;

    string strEID = _DataGrid.SelectedCells[0].Item.ToString(); 
}
于 2011-07-25T11:33:29.157 回答