【问题标题】:How to copy DataGrid cell value to clipboard如何将 DataGrid 单元格值复制到剪贴板
【发布时间】:2012-09-20 11:37:53
【问题描述】:

我有一个DataGrid。但我想在CopyingRowClipboardContent 事件中获得重点单元格值。但是由于SelectionUnite.ClipboardRowContent 会返回所有选定的单元格值。而且我不能更改数据网格的选择单元。为了解决这个问题,我需要获得重点单元格列号。然后我将从clipboarcContent 中删除所有列值。 如何在CopyingRowClipboardContent 事件中获得焦点单元格?

【问题讨论】:

    标签: c# wpf wpfdatagrid


    【解决方案1】:

    法哈德答案的改进版

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

    【讨论】:

    • 点击单元格会自动触发这个事件吗?
    【解决方案2】:

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

    Clipboard.SetText("some value");
    

    【讨论】:

      【解决方案3】:

      我找到了解决方案。 首先,我需要重点单元格的列号。我已经设法用这段代码得到它:

      DataGridResults.CurrentCell.Column.DisplayIndex;
      

      然后在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++;
              }
          }
      }
      

      【讨论】:

        【解决方案4】:

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

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

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2011-07-10
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2023-03-08
          相关资源
          最近更新 更多