繁体   English   中英

您如何遍历数据网格中 WPF 的选定单元格?

[英]How do you iterate through selected cells in datagrid for WPF?

我有一个数据网格,用户可以在其中 select 网格中单列的多个单元格,我想遍历选定的单元格并检索选定单元格行的第一列的值,但我已经卡在foreach 循环的第一步。 我之前在 WinForms 中使用 datagridview 做过这个,但似乎 WPF 是不同的。

foreach (DataGridCell cell in AppraiseeDataGrid.SelectedCells)//It says it cant convert type datagridcellinfo to datagricell

您必须遍历所有项目并确定是否选择了单元格,检查此代码:

foreach (DataGridCell cell in AppraiseeDataGrid.Items)
        {
            if (cell.IsSelected == true)
            {
                // Type your code here
            }
        }

DataGrid.SelectedCells在 WPF 中返回一个DataGridCellInfo

foreach (DataGridCellInfo cell in AppraiseeDataGrid.SelectedCells)
{
    DataGridColumn column = cell.Column;
    object dataRowItem = cell.Item;
}
string firstSelectedCellText = GetCellText(DataGrid.SelectedCells.First());

 private string GetCellText(DataGridCellInfo currentcellInfo)
        {
            var currentCell = GetDataGridCell(currentcellInfo);
            if (currentCell == null) return string.Empty;
            int itemIndex = DataGrid.Items.IndexOf(currentcellInfo.Item);
            DataGrid.CurrentCell = new DataGridCellInfo(DataGrid.Items[itemIndex], currentcellInfo.Column);
            if (currentCell.Content is TextBox textBox)
            {
                return textBox.Text;
            }
            if (currentCell.Content is TextBlock textBlock)
            {
                return textBlock.Text;
            }

            return string.Empty;
        }
  private DataGridCell GetDataGridCell(DataGridCellInfo cellInfo)
        {
            var cellContent = cellInfo.Column.GetCellContent(cellInfo.Item);
            if (cellContent != null)
                return (DataGridCell)cellContent.Parent;

            return null;
        }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM