Как скопировать значение ячейки DataGrid в буфер обмена

у меня есть DataGrid. Но я хочу получить сфокусированное значение ячейки в CopyingRowClipboardContent событие. Но!--2-- > возвращает мне все выбранные значения ячеек из-за SelectionUnit. И я не должен изменять единицу выбора datagrid. Для решения проблемы мне нужно сосредоточиться количество столбцов. Затем я удалю все значения столбцов из clipboarcContent. Как я могу получить сфокусированную ячейку в CopyingRowClipboardContent событие?

4 ответов


улучшенная версия ответа

private void DataGrid_CopyingRowClipboardContent(object sender, DataGridRowClipboardEventArgs e)
{
    var currentCell = e.ClipboardRowContent[ dataGrid.CurrentCell.Column.DisplayIndex];
    e.ClipboardRowContent.Clear();
    e.ClipboardRowContent.Add( currentCell );
}

вы также можете использовать следующий код для управления содержимым буфера обмена.

Clipboard.SetText("some value");

Я нашел решение. Прежде всего, мне нужен номер столбца сфокусированной ячейки. Мне удалось получить его с помощью этого кода:

DataGridResults.CurrentCell.Column.DisplayIndex;

затем в CopyingRowClipboardContent event, я должен удалить все остальные значения столбцов.

private void DataGridResults_CopyingRowClipboardContent(object sender, DataGridRowClipboardEventArgs e)
{
    int y = 0;

    for (int i = 0; i < e.EndColumnDisplayIndex; i++)
    {
        if (i != DataGridResults.CurrentCell.Column.DisplayIndex)
        {
            e.ClipboardRowContent.RemoveAt(i - y);
            y++;
        }
    }
}

Я обнаружил, что это решение работает для меня на все сетки данных; даже те, что были скрытые столбцы.

// Clipboard Row content only includes entries for visible cells
// Figure out the actual column we are looking for (taking into account hidden columns)
int columnIndex = dataGrid.CurrentCell.Column.DisplayIndex;
var column = dataGrid.Columns[columnIndex];

// Find the associated column we're interested in from the clipboard row content
var cellContent = clipboardRowContent.Where(item => item.Column == column).First();
clipboardRowContent.Clear();
clipboardRowContent.Add(cellContent);