簡體   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