首页 文章

在c#中的wpf中的datagrid中的单元格中设置值

提问于
浏览
0

我想在wpf中的特定单元格中设置一个值,我使用此代码,但getRow和getCell方法显示此错误

'DataGrid'不包含'GetRow'的定义,并且没有扩展方法'GetRow'可以找到接受类型'DataGrid'的第一个参数(你是否缺少using指令或汇编引用?)'DataGrid'不包含'GetCell'的定义,并且没有扩展方法'GetCell'接受类型'DataGrid'的第一个参数可以找到(你是否缺少using指令或汇编引用?)ControlSolution.Form

和公共部分类UCfrmRaafaLevelsUp中的错误:UserControl

必须在非泛型静态类中定义扩展方法

我使用它的代码

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

public static DataGridRow GetSelectedRow(this DataGrid grid)
{
    return (DataGridRow)grid.ItemContainerGenerator.ContainerFromItem(grid.SelectedItem);
}
public static DataGridRow GetRow(this DataGrid grid, int index)
{
    DataGridRow row = (DataGridRow)grid.ItemContainerGenerator.ContainerFromIndex(index);
    if (row == null)
    {
        // May be virtualized, bring into view and try again.
        grid.UpdateLayout();
        grid.ScrollIntoView(grid.Items[index]);
        row = (DataGridRow)grid.ItemContainerGenerator.ContainerFromIndex(index);
    }
    return row;
}

public static DataGridCell GetCell(this DataGrid grid, DataGridRow row, int column)
{
    if (row != null)
    {
        DataGridCellsPresenter presenter = GetVisualChild<DataGridCellsPresenter>(row);

        if (presenter == null)
        {
            grid.ScrollIntoView(row, grid.Columns[column]);
            presenter = GetVisualChild<DataGridCellsPresenter>(row);
        }

        DataGridCell cell = (DataGridCell)presenter.ItemContainerGenerator.ContainerFromIndex(column);
        return cell;
    }
    return null;
}

public static DataGridCell GetCell(this DataGrid grid, int row, int column)
{
    DataGridRow rowContainer = grid.GetRow(row);
    return grid.GetCell(rowContainer, column);
}

在这篇文章Change DataGrid cell value programmatically in WPF

2 回答

  • -1

    扩展方法是静态方法,在它们创建的类型上称为实例方法 . 例如:您创建的GetCell()方法 . 它使用DataGrid的引用来调用此方法 . 必须在单独的静态类中定义此类方法 . 将这些方法GetSelectedRow,GetCell,GetRow放在不同的静态类中,代码应该可以工作 .

  • 2

    扩展方法需要是继承链的一部分 . 如果你的方法是在一个单独的类(不是DataGrid,既不是父类,也不是它的子类),只需使它成为普通的静态方法,并静态调用此方法 .

    从逻辑上讲,您不能向DataGrid本身及其祖先类添加扩展方法,并且您似乎不是继承DataGrid,因此这不起作用 .

相关问题