WPF的DataGrid控件不能像winform的DataGridView控件一样,支持值的粘贴。WPF的DataGrid控件本质上是跟数据绑定联系在一起,所以需要进行复制粘贴的操作,可以在wpf里用DataGridView控件。如果想进行DataGrid的复制粘贴,只需要在进行复制粘贴的时候,将剪切板上的数据替换成绑定的数据,同样,插入删除等操作,都是改变绑定数据。如下,是一个粘贴的方法,将剪切板的数据转化为绑定数据。
- #region ctrl+c粘贴
- private void DataGirdViewCellPaste()
- {
- try
- {
- // 获取剪切板的内容,并按行分割
- string pasteText = Clipboard.GetText();
- if (string.IsNullOrEmpty(pasteText))
- return;
- int tnum = 0;//剪贴板列数
- int nnum = 0;//剪贴板行数
- //获得当前剪贴板内容的行、列数
- for (int i = 0; i < pasteText.Length; i++)
- {
- if (pasteText.Substring(i, 1) == "\t")
- {
- tnum++;
- }
- if (pasteText.Substring(i, 1) == "\n")
- {
- nnum++;
- }
- }
- Object[,] data;
- //粘贴板上的数据来自于EXCEL时,每行末都有\n,在DATAGRIDVIEW内复制时,最后一行末没有\n
- if (pasteText.Substring(pasteText.Length - 1, 1) == "\n")
- {
- nnum = nnum - 1;
- }
- tnum = tnum / (nnum + 1);
- data = new object[nnum + 1, tnum + 1];//定义一个二维数组
- String rowstr;
- rowstr = "";
- //MessageBox.Show(pasteText.IndexOf("B").ToString());
- //对数组赋值
- for (int i = 0; i < (nnum + 1); i++)
- {
- for (int colIndex = 0; colIndex < (tnum + 1); colIndex++)
- {
- //一行中的最后一列
- if (colIndex == tnum && pasteText.IndexOf("\r") != -1)
- {
- rowstr = pasteText.Substring(0, pasteText.IndexOf("\r"));
- }
- //最后一行的最后一列
- if (colIndex == tnum && pasteText.IndexOf("\r") == -1)
- {
- rowstr = pasteText.Substring(0);
- }
- //其他行列
- if (colIndex != tnum)
- {
- rowstr = pasteText.Substring(0, pasteText.IndexOf("\t"));
- pasteText = pasteText.Substring(pasteText.IndexOf("\t") + 1);
- }
- data[i, colIndex] = rowstr;
- }
- //截取下一行数据
- pasteText = pasteText.Substring(pasteText.IndexOf("\n") + 1);
- }
- //获取获取当前选中单元格所在的行序号
- int rowindex = dataGrid.SelectedIndex;
- List<BoxGriderModel> listBoxGriderModel = new List<BoxGriderModel>();
- for (int j = 0; j < (nnum + 1); j++)
- {
- listBoxGriderModel.Add(new BoxGriderModel(double.Parse(data[j, 0].ToString()), double.Parse(data[j, 1].ToString()), double.Parse(data[j, 2].ToString()), double.Parse(data[j, 3].ToString()),
- double.Parse(data[j, 4].ToString()), double.Parse(data[j, 5].ToString()), double.Parse(data[j, 6].ToString())));
- }
- m_model.ListBoxGriderModel = listBoxGriderModel;
- this.dataGrid.ItemsSource = m_model.ListBoxGriderModel;
- }
- catch
- {
- MessageBox.Show("粘贴区域大小不一致");
- return;
- }
- }
- #endregion
标签:
WPF Datagrid
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· 单线程的Redis速度为什么快?
· SQL Server 2025 AI相关能力初探
· AI编程工具终极对决:字节Trae VS Cursor,谁才是开发者新宠?
· 展开说说关于C#中ORM框架的用法!
2017-03-16 asp.net *.ashx类型的文件使用说明