【问题标题】:BeginEdit of a specific Cell from code behind从后面的代码开始编辑特定单元格
【发布时间】:2010-12-17 20:49:43
【问题描述】:

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

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

【问题讨论】:

    标签: wpf datagrid templates cell toolkit


    【解决方案1】:

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

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

    下面是从这里获取的 GetCell 方法的实现Grabing controls from a DataGrid

    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;
    } 
    

    希望这会有所帮助,问候

    【讨论】:

    • 我试了一下,效果很好!非常感谢!很有用的功能。
    • 我遇到了同样的问题。这段代码不能直接为我工作。但是,它只有在我从 Dispatcher.BeginInvoke 调用前几行时才有效,如下所示: Dispatcher.BeginInvoke(DispatcherPriority.Render, new Action(() => StartEditCurrentCell()));
    • 谢谢!这对我有用。
    猜你喜欢
    • 2013-09-20
    • 1970-01-01
    • 1970-01-01
    • 2020-08-18
    • 1970-01-01
    • 1970-01-01
    • 2018-06-20
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多