【WPF】遍历DataGrid

网上找了遍历DataGrid,但是都不能用,终于组合出来了~~

/// <summary>

/// 获取DataGrid遍历后的数据

/// </summary>

/// <param name="dg"></param>

/// <returns></returns>

public string DataGrid(DataGrid dg)
{
    try {
        string str = "";
        for (int j = 0; j < dg.Items.Count; j++)
        {
            DataGridCell c = DataGridHelper.GetCell(dg, j, 0);
            TextBlock tb = c.Content as TextBlock;
            if (str.Equals(string.Empty))
            {
                str = tb.Text;

             }
            else
            {
                str = str + "!" + tb.Text;//直接获取datagrid 遍历后的当前数据
            }
        }
         return str;
    }
    catch
    {
         return null;
    }
}


Class :

以下代码网上扒的~~~~

static class DataGridHelper{
    static public DataGridCell GetCell(DataGrid dg, int row, int column){
    DataGridRow rowContainer = GR(dg, row);
    if (rowContainer != null)
    {
        DataGridCellsPresenter p = GC<DataGridCellsPresenter>(rowContainer);
        DataGridCell cell = (DataGridCell)p.ItemContainerGenerator.ContainerFromIndex(column);
        if (cell == null)
        {
            dg.ScrollIntoView(rowContainer, dg.Columns[column]);
            cell = (DataGridCell)p.ItemContainerGenerator.ContainerFromIndex(column);
        }
        return cell;
    }
    else{
            return null;
        }
}

static public DataGridRow GR(DataGrid dg, int index){

    DataGridRow r = (DataGridRow)dg.ItemContainerGenerator.ContainerFromIndex(index);
    if (r == null)
    {

        dg.ScrollIntoView(dg.Items[index]);
        r = (DataGridRow)dg.ItemContainerGenerator.ContainerFromIndex(index);
    }
    return r;
}

static T GC<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 = GC<T>(v);
        }
        if (child != null)
        {
            break;
        }
    }
    return child;
}
}







            









       





 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值