【问题标题】:WPF,, How to make Datagrid cell Editable?WPF,, 如何使 Datagrid 单元格可编辑?
【发布时间】:2017-10-25 18:00:55
【问题描述】:

我想让数据网格列单元格可编辑,以便用户可以编写一些东西,并且我可以在变量后面的代码中获取该文本。我尝试添加它可以工作的文本框并在单元格中提供一个 extbox,但我无法在它给出空值的变量中获取键入的文本。我尝试了以下 在xml中

 <DataGridTextColumn Header="Result" Binding="{Binding Result}" Width="10*" ElementStyle="{StaticResource CenterAligned}" IsReadOnly="False">
                <DataGridTextColumn.CellStyle>
                    <Style TargetType="DataGridCell">
                        <Setter Property="Template">
                            <Setter.Value>
                                <ControlTemplate TargetType="DataGridCell">
                                    <TextBox Name="datagridTextBox" Style="{StaticResource basicTextBoxStyle}"></TextBox>
                                </ControlTemplate>
                            </Setter.Value>
                        </Setter>
                    </Style>
                </DataGridTextColumn.CellStyle>
            </DataGridTextColumn>  

在后面的代码中尝试了这个但没有成功,因为它返回 null

   for (int i = 0; i < AllTestsDataGrid.Items.Count; i++)
        {
            DataGridRow row = AllTestsDataGrid.ItemContainerGenerator.ContainerFromIndex(i) as DataGridRow;
  TextBox ele1 = ((ContentPresenter)(AllTestsDataGrid.Columns[2].GetCellContent(row))).Content as TextBox;
string value= ele1.Text;
}

请帮忙。提前致谢

【问题讨论】:

    标签: c# wpf datagrid


    【解决方案1】:

    在您的数据网格上启用此事件

    SelectionUnit="CellOrRowHeader" DataGridCell.Selected="Grid_Selected"
    

    然后在后面的代码中执行此操作。

            private void Grid_Selected(object sender, RoutedEventArgs e)
            {
                if (e.OriginalSource.GetType() == typeof(DataGridCell))
                {
                    DataGridCell cell = (e.OriginalSource as DataGridCell);
                    if (cell.IsReadOnly == true)
                        return;
                    // Starts the Edit on the row;
                    DataGrid grd = (DataGrid)sender;
                    grd.BeginEdit(e);
                    cell.IsEditing = true;
                    string cellValue = GetSelectedCellValue();
                }
            }
    
            public string GetSelectedCellValue()
            {
    
                DataGridCellInfo cells = Grid.SelectedCells[0];
    
                string columnName = cells.Column.SortMemberPath;
    
                var item = cells.Item;
    
                if (item == null || columnName == null) return null;
    
                object result = item.GetType().GetProperty(columnName).GetValue(item, null);
    
                if (result == null) return null;
    
                return result.ToString();
            }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-12-04
      • 2011-11-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-10-09
      相关资源
      最近更新 更多