wpf--获取单元格的内容

  最好的方法是使用Items属性并直接访问您的数据项:

var dataItem = dataGrid.Items[0] as …;
当然也可以直接通过数据源进行获取,应为datagrid绑定数据之后是同步的,但是如果一个数据源还没有数据,需要从前台输入的时候,这是后光标还在单元格里面,就需要使用下面这种方法了,可以获取行列,然后根据行列来获取,用于插入批次等情况,方便操作
但是您可以使用此类来获取单元格并使用GetValue()方法访问该值(更像您的示例).

代码取自此处:datagrid get cell index

private void dgv_PreviewKeyDown(object sender,KeyEventArgs e)
{
	if(e.Key==Key.Enter||e.Key==Key.Return)
	{
		int row=dgv.Items.IndexOf(dgv.CurrentItem);
		int col=dgv.Columns.IndexOf(dgv.currentColumn);
		//下面这个是获取单元格值的方法
		string CellValue=DataGridHelper.GetCell(dgv,row,col).split(":")[1];
	}
}

static class DataGridHelper {
    static public DataGridCell GetCell(DataGrid dg,int row,int column) {
        DataGridRow rowContainer = GetRow(dg,row);
 
        if (rowContainer != null) {
            DataGridCellsPresenter presenter = GetVisualChild<DataGridCellsPresenter>(rowContainer);
 
            // try to get the cell but it may possibly be virtualized
            DataGridCell cell = (DataGridCell)presenter.ItemContainerGenerator.ContainerFromIndex(column);
            if (cell == null) {
                // Now try to bring into view and retreive the cell
                dg.ScrollIntoView(rowContainer,dg.Columns[column]);
                cell = (DataGridCell)presenter.ItemContainerGenerator.ContainerFromIndex(column);
            }
            return cell;
        }
        return null;
    }
 
    static public DataGridRow GetRow(DataGrid dg,int index) {
        DataGridRow row = (DataGridRow)dg.ItemContainerGenerator.ContainerFromIndex(index);
        if (row == null) {
            // may be virtualized,bring into view and try again
            dg.ScrollIntoView(dg.Items[index]);
            row = (DataGridRow)dg.ItemContainerGenerator.ContainerFromIndex(index);
        }
        return row;
    }
 
    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);
            }
            if (child != null) {
                break;
            }
        }
        return child;
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值