前几天打算尝试下datagrid的用法,起初以为应该很简单,可后来被各种使用方法和功能实现所折磨。网络上的解决方法太多,但也太杂。没法子,我只好硬着头皮阅览各种文献资料,然后不断的去尝试,总算小有成果。因此,把我学到的和大家分享一下,相信这篇文章会让你再很短的时间内学会datagrid的大部分主要功能,而且很多难点都可以在里面找到解决方案。

由于涉及的应用比较多,所以篇幅会很长。但可以确保各个版块相互独立,总共4个部分

2.datagrid的增改删功能

3.datagrid的分页实现

4.datagrid的样式设计

先上一张截图,让你大概知道自己需要的功能是否在这张图里有所实现。

ps:使用技术:wpf + ado.net entity framework

 

 

 

1.数据绑定(涉及datagrid绑定和combox绑定)

 

在datagrid 中同时包含“自动生成列”与“用户自定义列” 由属性autogeneratecolumns控制。

默认情况下, datagrid 将根据数据源自动生成列。 下图列出了生成的列类型。

如果autogeneratecolumns=”true” ,我们只需要如下几行代码

<datagrid name=”datagrid1″ autogeneratecolumns=”true” />

后台datagrid1.itemssource = infolist; //infolist为内容集合(这是我从数据库中获取的记录集合 类型为list<t>)

ps:因为这里给datagrid1绑定了数据源,所以下面绑定的字段都是infolist中的字段名称,同样也对应着我数据表中的字段名。里面包含fid,公司名称,职员姓名,性别,年龄,职务。解释下,怕大家无法理解binding 后面的值是如何来的了

显然这种数据绑定非常的容易,如果对表格要求不高,这中无疑是最简单方便的。

 

如果autogeneratecolumns=”false” 表格字段的显示就要靠我们手动去完成了。这个也是数据绑定的重点,因为实际应用中我们大多都是自定义去完成datagrid的数据绑定。

接下来贴出代码(后面的所有功能都可以在此代码基础上添加和修改

<window x:class="csdn_c.mainwindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:assembly="clr-namespace:system;assembly=mscorlib" 
xmlns:local="clr-namespace:demo" 
title="mainwindow"  loaded="window_loaded">
<window.resources>
  <objectdataprovider x:key="keysex" methodname="getvalues" objecttype="{x:type assembly:enum}">
    <objectdataprovider.methodparameters>
      <x:type type="local:sex"></x:type>   <!--引用后台的枚举类型,为字段‘性别’提供数据源。上面引用了命名空间demo-->
    </objectdataprovider.methodparameters>
  </objectdataprovider>
</window.resources>
 
<grid> 
  <datagrid name="datagrid1"  autogeneratecolumns="false">
    <datagrid.columns>
      <datagridtemplatecolumn header="操作" width="40">
        <datagridtemplatecolumn.celltemplate>
          <datatemplate>
            <checkbox ></checkbox>
          </datatemplate>
        </datagridtemplatecolumn.celltemplate>
      </datagridtemplatecolumn>
      <datagridtextcolumn header="公司名称" width="80" binding="{binding 公司名称, mode=twoway, updatesourcetrigger=propertychanged}"/>
      <datagridtextcolumn header="姓名" width="80" binding="{binding 职员姓名, mode=twoway, updatesourcetrigger=propertychanged}"/>
      <datagridcomboboxcolumn header="sex" selecteditembinding="{binding 性别}" itemssource="{binding source={staticresource keysex}}"/>
      <!--combox绑定,获取上面定义的资源keysex.绑定性别-->
      <datagridtextcolumn header="年龄" width="80" binding="{binding 年龄, mode=twoway, updatesourcetrigger=propertychanged}"/>
      <datagridtextcolumn header="职务" width="80" binding="{binding 职务, mode=twoway, updatesourcetrigger=propertychanged}"/>
    </datagrid.columns>
  </datagrid>
</grid>
</window>

 

后台

namespace demo{
/// <summary>
/// mainwindow.xaml 的交互逻辑
/// </summary>
public enum sex { 男,女 };  //注意 写在命名空间内 ,不要写在类里,否则台前local:sex找不到路径
 
}

 

当我们绑定好数据运行程序的时候,会发现 datagridcomboboxcolumn下拉框里虽然绑定了值,但是他不会默认显示出已经设定好的值。所以我们就可以摈弃这种现有的 datagridcomboboxcolumn,我们用datagrid样板标签datagridtemplatecolumn

我们在datagridtemplatecolumn标签里要用到2个控件,一个 textblock控件来显示内容,另一个combox来提供选择。

所以我们可以用如下代码替换掉

<datagridcomboboxcolumn header=”sex” selecteditembinding=”{binding 性别}” itemssource=”{binding source={staticresource keysex}}”/>

<datagridtemplatecolumn header="性别">
                    <datagridtemplatecolumn.celltemplate>
                        <datatemplate>
                            <textblock text="{binding path=性别}"/>  <!--显示状态时显示 textblock里的值-->
                        </datatemplate>
                    </datagridtemplatecolumn.celltemplate>
                    <datagridtemplatecolumn.celleditingtemplate>
                        <datatemplate>  <!--编辑状态就切换到combobox里进行下拉选择操作-->
                            <combobox x:name="taskcombo" itemssource="{binding source={staticresource keysex}}"  selecteditem ="{binding path=性别}"  issynchronizedwithcurrentitem="false"/>
                        </datatemplate>
                    </datagridtemplatecolumn.celleditingtemplate>
                </datagridtemplatecolumn>

注意 celltemplate和 celleditingtemplate的区别

 

 

2.datagrid的增改删功能

  

①添加记录行+编辑记录行

 

由于增加和编辑有一定的联系,所以就放一起来讨论

在上面的代码处添加2个button按钮,datagrid默认是输入一行记录后自动会生成一个新行(类似mssql数据库添加表记录)。由属性 canuseraddrows来控制 当 canuseraddrows=false的时候就不会自动生成新行。为了方便我们自己来控制,所以在datagrid里面设置canuseraddrows为false.

<grid> 
  <button content="添加"   name="btnadd"  click=" btnadd_click" />
  <button content="保存"  name="btnsave" click="btnsave_click" />
  <datagrid name="datagrid1" autogeneratecolumns="false"  canuseraddrows="false">   <!--此时的datagrid就无法自己生成新行了-->
  </datagrid>
</grid>

 

后台事件

 int judge = 0;   //0表示编辑状态,1为添加状态。因为后面的增加和编辑都在同一个事件中,所以建一个变量来区分操作
 
 tb_information  tbinfo = new tb_information();    //这个类可以供我调用里面的方法来进行增删改查的操作
 
private void btnadd_click(object sender, routedeventargs e)
{
 
        judge = 1;  //现在为添加状态     
 
       datagrid1.canuseraddrows = true;    //点击添加后  将canuseraddrows重新设置为true,这样datagrid就会自动生成新行,我们就能在新行中输入数据了。
}
 
 
//现在我们可以添加新记录了,我们接下来要做的就是获取这些新添加的记录
 
//先声明一个存储新建记录集的list<t>      这里的information是我的数据表实体类  里面包含fid ,公司名称,职员姓名,性别,年龄,职务
 
 list<information> lstinformation = new list<information>();
 
//我们通过 roweditending来获取新增的记录,就是每次编辑完行后,行失去焦点激发该事件。   更新记录也是执行该事件
 
 private void datagrid1_roweditending(object sender, datagridroweditendingeventargs e)
{
     information info = new information();   //我自己的数据表实例类
      info = e.row.item as information;        //获取该行的记录
      if (judge == 1)                                          //如果是添加状态就保存该行的值到lstinformation中  这样我们就完成了新行值的获取
      {
          lstinformation.add(info);
      }
      else
      {  
          tbinfo.updinformation(info);            //如果是编辑状态就执行更新操作  更新操作最简单,因为你直接可以在datagrid里面进行编辑,编辑完成后执行这个事件就完成更新操作了
      }
}
 
 
 
//获取到记录后,单击保存按钮就可以保存lstinformation中的每一条记录
private void btnsave_click(object sender, routedeventargs e)
{
       foreach (information info in lstinformation)
       {
             tbinfo.insinformation(info);      //执行插入方法,将记录保存到数据库
      }
            judge = 0;          //重新回到编辑状态
            lstinformation.clear();
           datagrid1.canuseraddrows = false;     //因为完成了添加操作 所以设置datagrid不能自动生成新行了
           binding(num, 1);
}

 

这里又会遇到一个问题。那就是更新数据的时候,发现数据更本就没更新。跟踪代码会发现后台得到的值还是原来的,无法获取编辑后的值。这个问题就是绑定模式的问题,我们只需设置双向绑定就可以了。且作用对象是在属性值更改的情况下进行双向绑定。 只要在前面的每个表字段处加上 mode=twoway, updatesourcetrigger=propertychanged问题就解决了

例如: 

<datagridtextcolumn header="公司名称" width="80" binding="{binding 公司名称, mode=twoway, updatesourcetrigger=propertychanged}" />

 

②删除记录

 

为了有良好的用户体验,我就做了个可以批量删除的删除功能。就是利用到checkbox控件来完成。

以绑定代码为基础添加代码

<grid>
<button content="添加" name="btnadd" click="btnadd_click" />
<button content="保存" name="btnsave" click="btnsave_click" />
<button content="删除" name="btndelete" click="btndelete_click" />

</grid>

 

首先我们要获取checkbox中的值,有哪些是被选中的。显然checkbox里面还必须绑定值,并且还需要一个事件。给checkbox添加的代码如下

<datatemplate>
<checkbox click="checkbox_click" tag="{binding fid}" ></checkbox>
</datatemplate>

 

后台代码

//由checbox的click事件来记录被选中行的fid
 
 list<int> selectfid = new list<int>();  //保存选中要删除行的fid值
 
 private void checkbox_click(object sender, routedeventargs e)
{
     checkbox dg = sender as checkbox;
     int fid = int.parse(dg.tag.tostring());   //获取该行的fid
     var bl = dg.ischecked;
     if (bl == true)
     {
        selectfid.add(fid);         //如果选中就保存fid
     }
     else
     {
        selectfid.remove(fid);  //如果选中取消就删除里面的fid
    }
}
 
//已经获取到里面的值了,接下来就只要完成删除操作就可以了  删除事件如下
 
 private void btndelete_click(object sender, routedeventargs e)
{
     foreach (int fid in selectfid)
    {
         tbinfo.delinformation(fid);   //循环遍历删除里面的记录
    }
    //binding(num, 1);       //这个是我绑定的一个方法,作用是删除记录后重新给datagrid赋新的数据源
}

  

 

3.datagrid的分页实现

  
原理:其实分页功能的实现大家都清楚,无非就是把一个记录集通过运算来刷选里面对应页码的记录。

接来下我们再次添加新的代码

<grid>
<datagrid  name="datagrid1" autogeneratecolumns="false">
        <!--省略n个代码-->
</datagrid>
<stackpanel orientation="horizontal">
       <textblock text="转到" margin="5"/>
       <textbox name="tbxpagenum" text="" />
       <textblock text="页" />
       <button content="go"   click="btngo_click"/>
       <button name="btnup" content="上一页"  verticalalignment="center" click="btnup_click"/> 
       <button name="btnnext" content="下一页"  verticalalignment="center" click="btnnext_click"/>
       <textblock height="20">
             <textblock text="【共" />
             <textblock name="tbktotal" foreground="red" />
             <textblock text="页】" />
             <textblock text="【当前" />
             <textblock name="tbkcurrentsize" foreground="red" />
             <textblock text="页】" />
       </textblock>
</stackpanel>
</grid>

 

首先我们先写个分页的方法,供上面这些事件调用

后台代码

//number表示每个页面显示的记录数    currentsize表示当前显示页数
 
 private void binding(int number, int currentsize)
{
      list<information> infolist = new list<information>();
      infolist = tbinfo.getinformationlist();      //获取数据源
      int count = infolist.count;          //获取记录总数
      int pagesize = 0;            //pagesize表示总页数
      if (count % number == 0)
      {
           pagesize = count / number;
      }
      else
      {
           pagesize = count / number + 1;
      }
      tbktotal.text = pagesize.tostring();       
 
      tbkcurrentsize.text = currentsize.tostring();   
      infolist = infolist.take(number * currentsize).skip(number * (currentsize - 1)).tolist();   //刷选第currentsize页要显示的记录集
      datagrid1.itemssource = infolist;        //重新绑定datagrid1
}
 
 
 
//分页方法写好了 接下来就是响应下一页,上一页,和跳转页面的事件了
 
//先定义一个常量
 
 const int num=12;  //表示每页显示12条记录
 
//上一页事件 
 
 private void btnup_click(object sender, routedeventargs e)
{
     int currentsize = int.parse(tbkcurrentsize.text); //获取当前页数
     if (currentsize > 1)
     {
         binding(num, currentsize - 1);   //调用分页方法
     }
}
 
 
//下一页事件
private void btnnext_click(object sender, routedeventargs e)
{
     int total = int.parse(tbktotal.text); //总页数
     int currentsize = int.parse(tbkcurrentsize.text); //当前页数
     if (currentsize < total)
    {
        binding(num, currentsize + 1);   //调用分页方法
    }
}
 
 
//跳转事件
private void btngo_click(object sender, routedeventargs e)
{
    int pagenum = int.parse(tbxpagenum.text);
    int total = int.parse(tbktotal.text); //总页数
    if (pagenum >= 1 && pagenum <= total)
    {
       binding(num, pagenum);     //调用分页方法
    }
}

 

 

4.datagrid的样式设计

为什么用wpf,不就是因为wpf拥有绚丽的设计页面功能么(当然远不止这些)。虽然我美工这方面很差劲,但是最基本的设计我们还是要会一些。所以接下来做的工作主要就是给datagrid上色了。(有些需要用到后台代码,也许不属于样式这类,但总归是改变外观,所以就放在一起归纳了)

 

①给datagrid自动添加行序号+修改行表头颜色

 

后台代码

//窗体加载事件
 
 private void window_loaded(object sender, routedeventargs e)
{
    binding(num, 1);   //调用分页方法  显示第一页
    datagrid1.loadingrow += new eventhandler<datagridroweventargs>(datagrid_loadingrow);    //自动添加序号的事件  调用下面的datagrid_loadingrow
}
 
 public void datagrid_loadingrow(object sender, datagridroweventargs e)
{
        e.row.header = e.row.getindex() + 1;    //设置行表头的内容值
}

 

接下来就可以修改行表头的颜色了

<datagrid name="datagrid1">
   <datagrid.rowheaderstyle>
     <style targettype="datagridrowheader">
          <setter property="width" value="15"/>
          <setter property="background">
             <setter.value>
                  <lineargradientbrush startpoint="0,0" endpoint="1,1">
                       <gradientstop color="white" offset="0"/>     <!--这里用到了两种颜色  也可以多层  这样就可以产生一种渐变的效果或立体感-->
                       <gradientstop color="skyblue" offset="1"/>
                 </lineargradientbrush>
             </setter.value>
        </setter>
    </style>
  </datagrid.rowheaderstyle>
<!--省略n个代码-->
</datagrid>

 

②给列表头添加颜色

 

 <datagrid name="datagrid1">
<!--给整个表头添加颜色开始-->
          <datagrid.columnheaderstyle>
               <style targettype="datagridcolumnheader">
                    <setter property="background">
                         <setter.value>
                                <lineargradientbrush startpoint="0,0" endpoint="0,1">
                                        <gradientstop color="white" offset="0"/>
                                        <gradientstop color="lightblue" offset="0.5"/>
                                        <gradientstop color="white" offset="1"/>
                               </lineargradientbrush>
                         </setter.value>
                   </setter>
                   <setter property="foreground" value="black"/>
                   <setter property="fontsize" value="13" />
              </style>
         </datagrid.columnheaderstyle>
<!--给整个表头添加颜色结束-->
 
<!--给单个列表头添加颜色开始(以操作列表头为例)-->
          <datagrid.columns>
                <datagridtemplatecolumn header="操作" width="40">
                     <datagridcolumn.headerstyle>
                           <style targettype="datagridcolumnheader">
                                 <setter property="background">
                                       <setter.value>
                                             <lineargradientbrush startpoint="0,0" endpoint="0,1">
                                                   <gradientstop color="white" offset="0"/>
                                                   <gradientstop color="yellow" offset="0.5"/>
                                                   <gradientstop color="white" offset="1"/>
                                            </lineargradientbrush>
                                      </setter.value>
                                </setter>
                               <setter property="foreground" value="black"/>
                               <setter property="fontsize" value="13"/>
                               <setter property="width" value="70"/>
                          </style>
                    </datagridcolumn.headerstyle>
                </datagridtemplatecolumn>
          </datagrid.columns>
<!--给单个列表头添加颜色结束-->
<!--省略n个代码-->
</datagrid>

 

③给行添加颜色+滑鼠事件

 

<datagrid name="datagrid1">
     <datagrid.rowstyle>
         <style targettype="datagridrow">
                <setter property="background" value="lightblue" />
                <style.triggers>
                    <trigger property="ismouseover" value="true">     <!--当鼠标经过时 改变颜色-->
                         <setter property="background" value="skyblue"/>
                          <setter property="foreground" value="white"/>
                    </trigger>
              </style.triggers>
        </style>
    </datagrid.rowstyle>
 <!--省略n个代码-->
</datagrid>

 

④给单元格添加颜色

 

<datagrid name="datagrid1">
      <datagrid.cellstyle>
          <style targettype="datagridcell">
                <style.triggers>
                        <trigger property="isselected" value="true">     <!--单元格被选中时 改变颜色-->
                              <setter property="background" value="lightpink"/>
                        </trigger>
                </style.triggers>
          </style>
</datagrid.cellstyle>
 
<!--省略n个代码-->
</datagrid>

 
⑤ 让用户在单元格获得焦点时编辑 combobox

 

其实这不属于样式的范畴了,但我喜欢把改善用户体验归于这一类。当我们的表格里有类似combobox的控件时(如: datepicker 控件等)。我们编辑这些控件时,首先第一次单击获取单元格焦点,第二次点击才能获取编辑时的焦点,也就是用户必须单击2次才能进行操作。这种机制其实是适合文本框控件的,但对于其它控件,像combobox就显得很不方便了。所以我们要做的就是单击第一次的时候用户就可以编辑combobox。

接下来我要在datagrid添加了三个新属性(rowdetailsvisibilitymode、selectionmode 和 selectionunit)和一个新的事件处理程序 (selectedcellschanged)

前台

<datagrid name="datagrid1" canuseraddrows="false" autogeneratecolumns="false" roweditending="datagrid1_roweditending"rowdetailsvisibilitymode="visiblewhenselected" selectionmode="extended" selectionunit="cell" selectedcellschanged="datagrid1_selectedcellschanged" >

</datagrid>

 

后台

现在就差一个 selectedcellschanged(选则单元格时出发该事件)事件的后台代码了

private void datagrid1_selectedcellschanged(object sender, selectedcellschangedeventargs e)
{
     if (e.addedcells.count == 0)
          return;
     var currentcell = e.addedcells[0];
     if (currentcell.column == datagrid1.columns[3])   //columns[]从0开始  我这的combobox在第四列  所以为3
     {
            datagrid1.beginedit();    //  进入编辑模式  这样单击一次就可以选择combobox里面的值了
     }
}

 

⑥固定列表头

 

这个非常简单 只要在datagrid里添加一个属性即可

<datagrid frozencolumncount="1" >

<!--从1开始 1表示第一列 这里如果要固定我的操作列就设置为1-->

</datagrid>

by: