WPF中的DataGrid支持Excell粘贴数据
其中XMAL文件中的表格样式:
<DataGrid x:Name="DataListView" AutoGenerateColumns="False" HorizontalAlignment="Center" Margin="14,10,162,0" VerticalAlignment="Top" ItemsSource="{Binding }" CanUserAddRows="False" CanUserSortColumns="False" CanUserDeleteRows="False" Width="350" Height="239" SelectionMode="Extended" SelectionUnit="Cell">
<!-- This is required to handle CTRL + C when something is selected in the DataGrid -->
<DataGrid.CommandBindings>
<CommandBinding Command="Paste" Executed="PasteCommand" />
</DataGrid.CommandBindings>
<DataGrid.InputBindings>
<KeyBinding Key="V" Modifiers="Control" Command="Paste" />
</DataGrid.InputBindings>
<DataGrid.ColumnHeaderStyle>
<Style TargetType="DataGridColumnHeader">
<Setter Property="Background">
<Setter.Value>
<LinearGradientBrush StartPoint="0,0" EndPoint="0,1">
<GradientStop Color="White" Offset="0"/>
<GradientStop Color="Green" Offset="0.5"/>
<GradientStop Color="White" Offset="1"/>
</LinearGradientBrush>
</Setter.Value>
</Setter>
<Setter Property="Foreground" Value="Black"/>
<Setter Property="FontSize" Value="16" />
</Style>
</DataGrid.ColumnHeaderStyle>
<DataGrid.CellStyle>
<Style TargetType="DataGridCell">
<Style.Triggers >
<Trigger Property="IsSelected" Value="True">
<Setter Property="Background" Value="Snow"/>
<Setter Property="Foreground" Value="LimeGreen"/>
</Trigger>
</Style.Triggers>
</Style>
</DataGrid.CellStyle>
<DataGrid.Columns>
<!--UpdateSourceTrigger=PropertyChanged-->
<DataGridTextColumn Header="模块名称" Binding="{Binding Path=strModuleName,Mode=TwoWay,UpdateSourceTrigger=PropertyChanged}" MinWidth="80"/>
<DataGridTextColumn Header="最小值" Binding="{Binding Path=MinValue,Mode=TwoWay,UpdateSourceTrigger=PropertyChanged}" MinWidth="80" />
<DataGridTextColumn Header="最大值" Binding="{Binding Path=MaxValue,Mode=TwoWay,UpdateSourceTrigger=PropertyChanged}" MinWidth="80" />
<DataGridTextColumn Header="单位" Binding="{Binding Path=strUnit,Mode=TwoWay,UpdateSourceTrigger=PropertyChanged}" MinWidth="80" />
</DataGrid.Columns>
</DataGrid>
使用MVVM模式下的双向绑定,红色部分需要注意
后台代码如下:
/// <summary>
/// 粘贴处理剪贴板
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void PasteCommand(object sender, ExecutedRoutedEventArgs e)
{
// 获取剪切板的内容,并按行分割
string pasteText = Clipboard.GetText();
if (string.IsNullOrEmpty(pasteText))
return;
int cIndex = -1;
int rIndex = -1;
if (DataListView.SelectedCells.Count > 0)
{
DataGridCellInfo dgcInfo = DataListView.SelectedCells[0];
cIndex = dgcInfo.Column.DisplayIndex;
Dinfo dii = dgcInfo.Item as Dinfo;
rIndex = GetDinfoIndex(dii);
Console.WriteLine("("+ cIndex.ToString() + "," + rIndex.ToString() + ")");
}
string[] Rinfo = pasteText.Split(new string[]{"\r\n"}, StringSplitOptions.RemoveEmptyEntries);
if (cIndex > -1 && rIndex>-1)
{
int rSum = Math.Min(Rinfo.Length, DataListView.Items.Count - rIndex);
for(int i=0;i<rSum;i++ )
{
string[] Cinfo = Rinfo[i].Split(new string[] { "\t" }, StringSplitOptions.RemoveEmptyEntries);
int cSum = Math.Min(Cinfo.Length, DataListView.Columns.Count - cIndex);
for(int j=0;j<cSum;j++)
{
//Console.WriteLine("行:" + (rIndex + i).ToString());
//Console.WriteLine("列:" + (cIndex + j).ToString());
DataGridColumn dgcC = DataListView.Columns[cIndex + j];
//Dinfo dinfo = DataListView.Items[rIndex + i] as Dinfo;
try
{
(DataListView.Columns[cIndex + j].GetCellContent(DataListView.Items[rIndex + i]) as TextBlock).Text = Cinfo[j];
}
catch
{
}
}
}
//DataListView.Items.Refresh();
}
Console.WriteLine(pasteText);
}
private int GetDinfoIndex(Dinfo di)
{
if( displaydatas.Contains(di))
{
return displaydatas.IndexOf(di);
}
else
{
return -1;
}
}
模拟MVVM加载数据
private void Window_Loaded(object sender, RoutedEventArgs e)
{
Random rd = new Random();
for(int i=0;i<5;i++)
{
Dinfo di = new Dinfo();
di.MaxValue = 100 + rd.Next(0, 50);
di.MinValue = 10 + rd.Next(1, 80);
di.strModuleName = "模型" + i.ToString();
di.strUnit =(new[] {"C","%","-","dB","Km","Kg","mm","cm","#"})[rd.Next(0,8)];
displaydatas.Add(di);
}
DataListView.ItemsSource = displaydatas;
listView.Items.Clear();
listView.ItemsSource = displaydatas;
}
模型类:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace WpfAppShow
{
public class Dinfo: INotifyPropertyChanged
{
private string strmodulename;
private string strunit;
private int maxValue;
private int minValue;
public event PropertyChangedEventHandler PropertyChanged;
protected void OnPropertyChanged(string name)
{
PropertyChangedEventHandler handler = PropertyChanged;
if (handler != null)
{
handler(this, new PropertyChangedEventArgs(name));
}
}
public string strModuleName
{
get { return strmodulename; }
set
{
strmodulename = value;
OnPropertyChanged("strModuleName");
}
}
public string strUnit
{
get { return strunit; }
set
{
strunit = value;
OnPropertyChanged("strUnit");
}
}
public int MaxValue
{
get { return maxValue; }
set
{
maxValue = value;
OnPropertyChanged("MaxValue");
}
}
public int MinValue
{
get { return minValue; }
set
{
minValue = value;
OnPropertyChanged("MinValue");
}
}
}
}
WPF中的DataGrid支持Excell粘贴数据的更多相关文章
- WPF 中获取DataGrid 模板列中控件的对像
WPF 中获取DataGrid 模板列中控件的对像 #region 当前选定行的TextBox获得焦点 /// <summary> /// 当前选定行的TextBox获得焦点 /// &l ...
- wpf中的datagrid绑定操作按钮是否显示或者隐藏
如图,需要在wpf中的datagrid的操作那列有个确认按钮,然后在某些条件下确认按钮可见,某些情况下不可见的,放在mvc里直接在cshtml页面中if..else就行了. 但是在wpf里不行..网上 ...
- wpf中为DataGrid添加checkbox支持多选全选
项目中用到DataGrid, 需要在第一列添加checkbox, 可以多选.全选. 其中涉及的概念DataTemplate, DataGridCellStyle, DataGridCellContro ...
- 不注册COM在Richedit中使OLE支持复制粘贴
正常情况下在Richedit中使用OLE,如果需要OLE支持复制粘贴,那么这个OLE对象必须是已经注册的COM对象. 注册COM很简单,关键问题在于注册时需要管理员权限,这样一来,如果希望APP做成绿 ...
- 扩展ArcGIS API for Silverlight/WPF 中的TextSymbol支持角度标注
原文 http://blog.csdn.net/esricd/article/details/7587136 在ArcGIS API for Silverlight/WPF中原版的TextSymbol ...
- WPF中退出时显示是否保存数据提示
一.通过窗体中的按钮实现退出时数据保存提示 Xaml: <Grid> <TextBlock HorizontalAlignment="Left" Margin=& ...
- Wpf 中的DataGrid的Header属性,动态bind时不起作用
在使用wpf开发软件时,有使用到DataGrid,DataGridTextColumn的Header 属性使用DynamicResource binding,在修改绑定数据源时,header并没有更新 ...
- WPF中使用DataGrid时操作列按钮问题
在使用DataGrid的过程中,我们有时候需要对选取的某一行数据进行多个操作,这个时候操作列只有一个按钮显然无法满足我们的要求,我们需要多个按钮才能达到我们的目的. UI页面代码: <Grid& ...
- (转帖)关于easyui中的datagrid在加载数据时候报错:无法获取属性"Length"的值,对象为null或未定义
结贴说明: 很感谢sp1234等人的热心帮忙和提醒,现在我主要说明下问题所在: 首先我在独立的js文件中,直接把测试数据loaddata进去datagrid是没有问题的.var kk = {" ...
- WPF中修改DataGrid单元格值并保存
编辑DataGrid中的单元格的内容然后保存是非常常用的功能.主要涉及到的方法就是DataGrid的CellEditEnding 和BeginningEdit .其中BeginningEdit 是当 ...
随机推荐
- stm32 窗口看门狗
窗口看门狗一般要在几十毫秒后开始喂狗 窗口看门狗在执行0x40时会调用回调函数, 回调函数可以执行喂门狗,否则会执行到0x3F直接复位 参考链接: https://blog.csdn.net/weix ...
- 谈谈 Redis 的过期策略
在日常开发中,我们使用 Redis 存储 key 时通常会设置一个过期时间,但是 Redis 是怎么删除过期的 key,而且 Redis 是单线程的,删除 key 会不会造成阻塞.要搞清楚这些,就要了 ...
- misc1 ---攻防世界
题目: 应该是一串16进制的字符串: 但得到的是一堆乱码,于是查阅发现是偏移了128 str="d4e8e1f4a0f7e1f3a0e6e1f3f4a1a0d4e8e5a0e6ece1e7a ...
- Unity 纯C# 完成 APK从下载到 自安装
最简单的就是用androidStudio 进行编辑,打个aar 包,在Unity中调用方法,很便捷以下内容均转载Unity论坛,Android API24版本下可用,android API 24以上版 ...
- async await和promise的区别,和使用方法
async和promise都是异步方法,区别是async生成的结果是promise对象,async是promise的终结版. await只能在async中使用,await是阻塞的意思,就是暂停,你一起 ...
- Sentinel 高可用流量管理框架
出处:https://www.oschina.net/p/sentinel?hmsr=aladdin1e1 Sentinel 是面向分布式服务架构的高可用流量防护组件,主要以流量为切入点,从限流.流量 ...
- VUE 一些小功能(查重、逻辑删除)
查重就是在表中查找是否有该值,如果有返回0没有则返回1 在API写添加方法时可以直接通过该方法返回值进行添加,如果是0则添加,1则重名 不进行添加 逻辑删除就是在信息表中添加一个删除状态的字段,比 ...
- 数据库负载均衡 happroxy 中间器(Nginx)容器的安装与配置
docker 镜像中安装haproxy 1.下载并安装haproxy镜像 docker pull happroxy # docker pull haproxy:1.7 2.查看镜像 docker i ...
- 七牛云服务器debug
400{ResponseInfo:com.qiniu.http.Response@16fd3806,status:400, reqId:uzcAADGFlzHUE-kW, xlog:-, xvia:, ...
- You Don't Know JS阅读笔记
JS特性查漏补缺 [1,2,3]=="1,2,3" //true 前者会隐式转换,用逗号组合成字符串 212>'22' //true 有一个值不是number就会隐式转换成n ...