WPF ,,如何使Datagrid单元格可编辑?

时间:2017-10-25 18:00:55

标签: c# wpf datagrid

我想让datagrid列单元格可编辑,以便用户可以编写一些内容,我可以在代码后面的变量中获取该文本。我试图添加它工作的文本框并在单元格中提供一个extbox但我无法在变量中获取类型文本它给出null值。我尝试了以下内容 在xaml

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

请帮忙。提前致谢

1 个答案:

答案 0 :(得分:0)

在数据网格上启用此事件

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