从 Datagrid 中获得单元格的内容

DataGrid 属于一种 ItemsControl, 因此,它有 Items 属性并且用ItemContainer 封装它的 items. 但是,WPF中的DataGrid 不同于Windows Forms中的 DataGridView。 在DataGrid的Items集合中,DataGridRow是一个Item,但是,它里面的单元格却是被封装在 DataGridCellsPresenter 的容器中;因此,我们不能使用像DataGridView.Rows.Cells 这样的语句去获得单元格的内容。但是,在WPF中我们可以通过可视树(VisualTree)去进入到控件“内部“, 那么,我们当然可以通过VisualTree进入DataGrid中的 DataGridRowDataGridCellsPresenter,并且得到在DataGridCellsPresenter中的实例, 大家可以通过以下的代码遍历VisualTree。

DataGridRow rowContainer = (DataGridRow)dataGrid1.ItemContainerGenerator.ContainerFromIndex(rowIndex); 
DataGridCellsPresenter presenter = GetVisualChild<DataGridCellsPresenter>(rowContainer); 
DataGridCell cell = (DataGridCell)presenter.ItemContainerGenerator.ContainerFromIndex(columnIndex); 
 
// ...
 
public static T GetVisualChild<T>(Visual parent) where T : Visual 
{ 
  T child = default(T); 
  int numVisuals = VisualTreeHelper.GetChildrenCount(parent); 
 
  for (int i = 0; i < numVisuals; i++) 
  { 
    Visual v = (Visual)VisualTreeHelper.GetChild(parent, i); 
    child = v as T; 
    
    if (child == null) 
      child = GetVisualChild<T>(v); 
    else
      break; 
  } 
 
  return child; 
}

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值