zoukankan      html  css  js  c++  java
  • WPF DataGrid 获取选中 一行 或者 多行

    WPF中DataGrid使用时,需要将其SelectedItem转换成DataRowView进行操作

    然而SelectedItem SelectedItems DataGrid的SelectionUnitSelectionMode两个属性的取值不同时有变化

    一:当DataGrid.SelectionUnit == DataGridSelectionUnit.FullRow时,获取选中一行与多行的方法:

    1选中多行

    int count = DataGrid.SelectedItems.Count;  

     DataRowView[] drv = new DataRowView[count];  

     for (int i = 0; i < count; i++)  

      {  

       drv[i] = DataGrid.SelectedItems[i] as DataRowView;  

     }  

      return drv;  

    2选中一行

    DataGrid.SelectedItem as DataRowView  

     

    二:但是当DataGrid.SelectionUnit 的属性是Cell或者CellOrRowHeader时,并且SelectionMode的值为 Extented时,这样处理就不太好。因为如果选中的是 cell 则SelectedItem的值为null。所以可以通过Cell来统一处理,无论SelectionUnit 的值是什么,总有选中的单元格,通过单元格确定该行。

    private DataRowView GetSelectedRow()  

     {  

             /*优化  

      * 无论 DataGrid的SelectionUnit跟SelectionMode两个属性取任何值 

    * 都存在选中的单元格 

    * 可以根据选中的单元格做统一处理,获取选中的行 

     *  GetSelectedRows()方法获取选中多行原理相同 

    */  

             if (DataGrid != null && DataGrid.SelectedCells.Count != 0)  

      {  

        //只选中一个单元格时:返回单元格所在行  

    //选中多个时:返回第一个单元格所在行  

       return DataGrid.SelectedCells[0].Item as DataRowView;  

      }  

     

        return null;  

      }  

    /// <summary>  

    /// 私有方法 获取选中的多行  

    /// </summary>  

      /// <returns></returns>  

      private DataRowView[] GetSelectedRows()  

     {  

     //当选中有多个单元格时,获取选中单元格所在行的数组  

     //排除数组中相同的行  

    if (DataGrid!=null&&DataGrid.SelectedCells.Count > 0)  

    {  

     DataRowView[] dv = new DataRowView[DataGrid.SelectedCells.Count];  

     for (int i = 0; i < DataGrid.SelectedCells.Count; i++)  

     {  

    dv[i] = DataGrid.SelectedCells[i].Item as DataRowView;  

                 }  

    //因为选中的单元格可能在同一行的,需要排除重复的行  

      return dv.Distinct().ToArray();  

      }  

     return null;  

         }  

  • 相关阅读:
    Linux块设备IO子系统(二) _页高速缓存
    Linux块设备IO子系统(一) _驱动模型
    Linux usb子系统(二) _usb-skeleton.c精析
    Linux usb子系统(一) _写一个usb鼠标驱动
    Linux i2c子系统(四) _从i2c-s3c24xx.c看i2c控制器驱动的编写
    Linux i2c子系统(三) _解决probe无法执行
    Linux i2c子系统(二) _通过i2c-dev.c访问设备的方法
    Linux i2c子系统(一) _动手写一个i2c设备驱动
    从0移植uboot(六) _实现网络功能
    从0移植uboot(五) _实现串口输出
  • 原文地址:https://www.cnblogs.com/sjqq/p/6950978.html
Copyright © 2011-2022 走看看