2009-11-18 43 views
1

是否可以從DataGrid控件(WPF Toolkit)的後面代碼開始編輯特定單元格?BeginEdit from code behind

我必須啓用按鈕操作後選定行的第一個單元格的celledittemplate ......我該怎麼辦?

回答

8

請,嘗試把下面的代碼在按鈕的上單擊事件處理程序:

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

希望這有助於拍攝,視

+0

我嘗試它的工作原理!非常感謝你! 非常有用的功能。 – 2009-11-19 08:06:26

+0

我遇到了同樣的問題。此代碼不適用於我直接。但是,它只在調用Dispatcher.BeginInvoke的前幾行時才起作用,如下所示:Dispatcher.BeginInvoke(DispatcherPriority.Render,new Action(()=> StartEditCurrentCell())); – newman 2010-10-25 14:12:38

相關問題