这是一个可能对您有所帮助的代码片段。此代码段主要用于检索您选择的所有数据,包括标题(我删除了该RowHeaders
部分,因为您显然不需要它)。如果您有任何问题,请告诉我。我留下了一些用大写字母写的注释:这是您应该添加自己的数据的地方 这种方法的好处是它直接与您DataGrid
的 'sItemsSource
而不是DataGridCell
. 主要原因是:DataGridCell
例如,如果您使用格式化的数字,您将不会获得实际值,而只会获得格式化的值(假设您的源是 14.49,而您的源StringFormat
是 N0,如果您使用 "常规”方式)
/// <summary>
/// Handles DataGrid copying with headers
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void OnCopyingDataGrid(object sender, ExecutedRoutedEventArgs e)
{
// First step: getting the coordinates list of all cells selected
IList<Tuple<int, int>> cellsCoordinatesList = new List<Tuple<int, int>>();
HashSet<int> rowList = new HashSet<int>();
HashSet<int> columnList = new HashSet<int>();
foreach (System.Windows.Controls.DataGridCellInfo cell in this.SelectedCells)
{
int column = cell.Column.DisplayIndex;
int row = this.Items.IndexOf(cell.Item);
cellsCoordinatesList.Add(new Tuple<int, int>(row, column));
if (!rowList.Contains(row))
{
rowList.Add(row);
}
if (!columnList.Contains(column))
{
columnList.Add(column);
}
}
// Second step: Create the table to copy/paste
object[,] arrayToBeCopied = new object[rowList.Count, columnList.Count + 1];
IList<string> colHead = this.ColumnHeaders.Cast<object>().Select(h => h.ToString()).ToList();
for (int row = 0; row < arrayToBeCopied.GetLength(0); row++)
{
for (int column = 0; column < arrayToBeCopied.GetLength(1); column++)
{
if (row == 0)
{
arrayToBeCopied[row, column] = colHead[columnList.ElementAt(column - 1)];
}
else
{
arrayToBeCopied[row, column] = // WHATEVER YOU WANT TO PUT IN THE CLIPBOARD SHOULD BE HERE. THIS SHOULD GET SOME PROPERTY IN YOUR ITEMSSOURCE
}
}
}
// Third step: Converting it into a string
StringBuilder sb = new StringBuilder();
// HERE, ADD YOUR FIRST ROW BEFORE STARTING TO PARSE THE COPIED DATA
for (int row = 0; row < arrayToBeCopied.GetLength(0); row++)
{
for (int column = 0; column < arrayToBeCopied.GetLength(1); column++)
{
sb.Append(arrayToBeCopied[row, column]);
if (column < arrayToBeCopied.GetLength(1) - 1)
{
sb.Append("\t");
}
}
sb.Append("\r\n");
}
// AND HERE, ADD YOUR LAST ROWS BEFORE SETTING THE DATA TO CLIPBOARD
DataObject data = new DataObject();
data.SetData(DataFormats.Text, sb.ToString());
Clipboard.SetDataObject(data);
}