wpf 如何将 DataGrid 单元格值复制到剪贴板

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12511809/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-13 05:26:44  来源:igfitidea点击:

How to copy DataGrid cell value to clipboard

c#wpfwpfdatagrid

提问by Farhad Jabiyev

I have a DataGrid. But I want to get focused cell value in CopyingRowClipboardContentevent. But e.ClipboardRowContentreturns me all selected cells values because of the SelectionUnit. And i must not change selection unit of datagrid. For solving the problem i need to get focused cell column number. Then I will remove all column values from clipboarcContent. How can i get focused cell in CopyingRowClipboardContentevent?

我有一个DataGrid. 但我想在CopyingRowClipboardContent事件中获得焦点单元格值。但是e.ClipboardRowContent由于SelectionUnit. 而且我不能改变数据网格的选择单位。为了解决这个问题,我需要获得重点单元格列号。然后我将从中删除所有列值clipboarcContent。我怎样才能在CopyingRowClipboardContent事件中获得焦点单元格?

回答by Denis Besic

Improved version of Farhad's answer

Farhad 答案的改进版本

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

回答by Hamid

You can also use the following code in order control clipboard content.

您还可以使用以下代码来控制剪贴板内容。

Clipboard.SetText("some value");

回答by Farhad Jabiyev

I find the solution. First of all I have needed column number of the focused cell. I have managed to get it with this code:

我找到了解决办法。首先,我需要聚焦单元格的列号。我设法用这个代码得到它:

DataGridResults.CurrentCell.Column.DisplayIndex;

Then in CopyingRowClipboardContentevent, I must delete all other column values.

然后CopyingRowClipboardContent,我必须删除所有其他列值。

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++;
        }
    }
}

回答by JohnB

I found that this solution worked for me on all DataGrids; even ones that had hidden columns.

我发现这个解决方案适用于所有 DataGrids;甚至那些有隐藏列的。

// 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);