WPF Datagrid支持单元格内容复制(同时能够选择整行)

扩展类库源码

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
using System.Windows.Media;

namespace GridView行选复制单元格
{
    public class DataGridExt : DataGrid
    {
        private bool IsCopying = false;
        public string CellText = string.Empty;
        public DataGridExt()
        {
            this.SelectedCellsChanged += DataGridExt_SelectedCellsChanged;
            this.KeyUp += DataGridExt_KeyUp;
        }

        private void DataGridExt_KeyUp(object sender, KeyEventArgs e)
        {
            if (Keyboard.Modifiers == ModifierKeys.Control && e.Key == Key.C && !string.IsNullOrEmpty(CellText))
            {
                Clipboard.SetText(CellText);
                CellText = string.Empty;
                e.Handled = false;
            }
        }

        private void DataGridExt_SelectedCellsChanged(object sender, SelectedCellsChangedEventArgs e)
        {
            var cells = this.SelectedCells;
            if (cells == null || cells.Count == 0) return;
            var index = this.Items.IndexOf(cells.First().Item);
            CellText = GetCellText();
            this.SelectedIndex = index;
            IsCopying = false;
        }
        private string GetCellText()
        {
            if (IsCopying) return CellText;
            IsCopying = true;
            var list = this.SelectedCells;
            var cellinfo = list.LastOrDefault();
            if (cellinfo == null || cellinfo.Column == null) return CellText;
            if (cellinfo.Column.GetType() == typeof(DataGridTextColumn))
            {
                var text = ((TextBlock)cellinfo.Column.GetCellContent(cellinfo.Item)).Text;
                return text;
            }
            //如果需要处理其他类型的列,请在这里添加更多的if分支或者增加决策类

            return String.Empty;
        }
    }
}

用法

<Window x:Class="GridView行选复制单元格.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:local="clr-namespace:GridView行选复制单元格"
        mc:Ignorable="d"
        Title="MainWindow" Height="450" Width="800"> 
    <Grid>
        <Grid.RowDefinitions>
            <RowDefinition/>
            <RowDefinition/>
            <RowDefinition Height="30"/>
        </Grid.RowDefinitions> 
        <local:DataGridExt  Grid.Row="1" AutoGenerateColumns="True" SelectionMode="Single" SelectionUnit="CellOrRowHeader" 
                  ItemsSource="{Binding}">
            
        </local:DataGridExt>
        <TextBox Width="200" Grid.Row="2"/>
    </Grid>
</Window>

效果

在这里插入图片描述

源代码

https://github.com/iml6yu/WPF_Datagrid_Cell_Copy

基本思路

原有程序很多对Datagrid的使用都是整行选中的效果,但是不能进行单元格复制,所以需要对类进行扩展,能够满足整行选择的效果,还能够复制单元。

  1. 当选中单元格时把数据赋值给一个临时变量,并且再将选择状态设置为选中整行
  2. 按下ctrl+c的时候把临时变量内容写入剪切板

that is all

要实现 WPF DataGrid 中选中单元格或列头选中整列,并更换背景颜色,可以使用以下代码: 1. 在 DataGrid 标签中添加 SelectionUnit="Cell" 属性,以确保单元格被选中时整行不会被选中。 2. 在 DataGrid 中添加 SelectionChanged 事件,以便在选中单元格时更改单元格背景颜色。 3. 在 DataGrid 中添加 MouseLeftButtonDown 事件,以便在单击列头时更改整列的背景颜色。 以下是示例代码: ```xml <DataGrid SelectionUnit="Cell" SelectionChanged="DataGrid_SelectionChanged" MouseLeftButtonDown="DataGrid_MouseLeftButtonDown"> <DataGrid.Resources> <SolidColorBrush x:Key="SelectedBackgroundBrush" Color="LightBlue"/> </DataGrid.Resources> <DataGrid.CellStyle> <Style TargetType="{x:Type DataGridCell}"> <Style.Triggers> <Trigger Property="IsSelected" Value="True"> <Setter Property="Background" Value="{StaticResource SelectedBackgroundBrush}"/> </Trigger> </Style.Triggers> </Style> </DataGrid.CellStyle> <DataGrid.ColumnHeaderStyle> <Style TargetType="{x:Type DataGridColumnHeader}"> <EventSetter Event="MouseLeftButtonDown" Handler="DataGrid_MouseLeftButtonDown"/> </Style> </DataGrid.ColumnHeaderStyle> </DataGrid> ``` 在代码中,我们定义了一个名为 SelectedBackgroundBrush 的资源,用于存储选中单元格的背景颜色。然后,我们使用 CellStyle 触发器来更改选中单元格的背景颜色。我们还使用 ColumnHeaderStyle 事件设置器来处理列头的 MouseLeftButtonDown 事件,以更改整列的背景颜色。 在代码后台,我们可以使用以下代码来更改整列的背景颜色: ```csharp private void DataGrid_MouseLeftButtonDown(object sender, MouseButtonEventArgs e) { if (e.ClickCount == 1) { var columnHeader = e.OriginalSource as DataGridColumnHeader; if (columnHeader != null) { var column = columnHeader.Column; var cells = column.GetCellContent(DataGrid.Columns[column.DisplayIndex].GetCellContent(DataGrid.SelectedItem as DependencyObject)).Parent as DataGridCellsPresenter; foreach (var cell in cells.Items) { var dataGridCell = cell as DataGridCell; dataGridCell.Background = (SolidColorBrush)Resources["SelectedBackgroundBrush"]; } } } } ``` 在代码后台,我们使用 DataGridColumnHeader 实例、列索引和 DataGridCellsPresenter 实例来获取整列的所有单元格,并更改它们的背景颜色。
评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值