WPF:如何启用第一列中的 DataGrid ID 单元格在从代码中突出显示时可编辑?

Hui Liu-MSFT 38,331 信誉分 Microsoft 供应商
2024-04-17T08:13:08.0433333+00:00

我们的应用程序是 WPF 应用程序。在一个页面中,有两个控件。 一个控件是 WPF DataGrid,它包含 5 列。只有第一列和最后一列是可编辑的。 第一列表示 ID,第五列表示注释。DataGrid 包括 96 行。

另一个对照是板,它包括 96 个孔,显示为 8 行 X 12 列 = 96 个孔。

当我们在板控件中单击一个孔时,它会自动突出显示 DataGrid 控件中具有相同 ID 的相关行。 如果单击第一列突出显示 ID 单元格,则不会将该单元格显示为可编辑单元格。我们必须第二次单击才能使其可编辑(请参阅突出显示 ID 单元格上的光标)。 我们需要一种方法,如果 DataGrid 行突出显示,请单击该行中的第一个单元格以允许以正确方式键入。 我们在 DataGrid 中添加了以下事件。


DataGridCell.Selected="DataGrid_CellGotFocus"

private void DataGrid_CellGotFocus(object sender, RoutedEventArgs e)
{
// Lookup for the source to be DataGridCell
if (e.OriginalSource.GetType() == typeof(DataGridCell))
{
// Starts the Edit on the row;
DataGrid grd = (DataGrid)sender;
grd.BeginEdit(e);
Debug.Print("DataGrid_CellGotFocus: " + e.OriginalSource.ToString());
}
}

如果 ID 单元格处于可编辑模式,请在之前或之后单击下一个 ID 单元格,它使所选单元格可以正确编辑。 但是,如果焦点在板控件上,则第一次单击突出显示的 ID 单元格,它不会显示为可编辑,我们必须单击第二次。 有谁知道如何解决这个问题,谢谢!

Note:此问题总结整理于:WPF: how to enable DataGrid ID cells in first column editable when highlight it from code?

Windows Presentation Foundation
Windows Presentation Foundation
.NET Framework 的一部分,它提供统一的编程模型,用于在 Windows 上构建业务线桌面应用程序。
53 个问题
0 个注释 无注释
{count} 票

接受的答案
  1. Jiale Xue - MSFT 32,076 信誉分 Microsoft 供应商
    2024-04-17T08:52:45.6166667+00:00

    可以使用以下代码使 DataGridCell 可编辑:

     private void DataGridCell_GotFocus(object sender, RoutedEventArgs e)  
            {  
      
                DataGridCell cell = sender as DataGridCell;  
                EditCell(cell, e);  
                Debug.Print("DataGrid_CellGotFocus: " + e.OriginalSource.ToString())  
            }  
      
      
            private void EditCell(DataGridCell cell, RoutedEventArgs e)  
            {  
                if (cell == null || cell.IsEditing || cell.IsReadOnly)  
                    return;  
      
                if (!cell.IsFocused)  
                {  
                    cell.Focus();  
                }  
                MyDataGrid.BeginEdit(e);  
                cell.Dispatcher.Invoke( DispatcherPriority.Background, new Action(delegate { })  
                );  
      
            }  
    

    如果回复有帮助,请点击“接受答案”并点赞。

    注意:如果您想接收此线程的相关电子邮件通知,请按照我们文档中的步骤启用电子邮件通知。

    0 个注释 无注释

0 个其他答案

排序依据: 非常有帮助