来自代码的特定Cell的BeginEdit

时间:2009-11-18 12:58:46

标签: wpf datagrid templates cell toolkit

是否可以使用DataGrid控件(WPF Toolkit)从代码后面开始编辑特定单元格?

我必须在按钮操作后启用所选行的第一个单元格的celledittemplate ...我该怎么办?

1 个答案:

答案 0 :(得分:8)

请尝试将下面的代码放在点击事件处理程序的按钮上:

    DataGridCell cell = GetCell(1, 0);
    if (cell != null)
    {
        cell.Focus();
        yourDataGrid.BeginEdit();
    }
下面的

是从这里Grabing controls from a DataGrid

获取的GetCell方法的实现
public DataGridCell GetCell(int row, int column)
{
    DataGridRow rowContainer = GetRow(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
            gridPersons.ScrollIntoView(rowContainer, gridPersons.Columns[column]);
            cell = (DataGridCell)presenter.ItemContainerGenerator.ContainerFromIndex(column);
        }
        return cell;
    }
    return null;
}

public DataGridRow GetRow(int index)
{
    DataGridRow row = (DataGridRow)gridPersons.ItemContainerGenerator.ContainerFromIndex(index);
    if (row == null)
    {
        // may be virtualized, bring into view and try again
        gridPersons.ScrollIntoView(gridPersons.Items[index]);
        row = (DataGridRow)gridPersons.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;
} 

希望这有帮助,尊重