如何在WPF网格中获取选定的列名称或索引

时间:2011-08-08 13:27:31

标签: c# wpf xaml

您能否告诉我如何在WPF网格中获取选定的列名称或索引。

3 个答案:

答案 0 :(得分:1)

对于DataGrid,您可以通过CurrentCell属性获取该列:

DataGridCellInfo cellInfo = dataGrid.CurrentCell;
DataGridColumn column=cellInfo.Column;

答案 1 :(得分:0)

尝试此选项以获取所选行的列表:

IList rows = dg.SelectedItems;

来自this related question

答案 2 :(得分:0)

这就是我们如何获得特定细胞的价值

Object obj = GetCell(3).Content;
                     string cellContent = String.Empty;
                     if (obj != null)
                     {
                         if (obj is TextBox)
                             cellContent = ((TextBox)(obj)).Text;
                         else
                             cellContent = ((TextBlock)(obj)).Text;
                      }




private DataGridCell GetCell(int column)
    {
        DataGridRow rowContainer = GetRow();

        if (rowContainer != null)
        {
            DataGridCellsPresenter presenter = GetVisualChild<DataGridCellsPresenter>(rowContainer);

            // Try to get the cell but it may possibly be virtualized.
            DataGridCell cell = (DataGridCell)presenter.ItemContainerGenerator.ContainerFromIndex(column);
            if (cell == null)
            {
                // Now try to bring into view and retreive the cell.
                customDataGrid.UCdataGridView.ScrollIntoView(rowContainer, customDataGrid.UCdataGridView.Columns[column]);
                cell = (DataGridCell)presenter.ItemContainerGenerator.ContainerFromIndex(column);
            }
            return cell;
        }
        return null;
    }