Editing a WPF Datagrid Cell

When I bind my ObservableCollection to my DataGrid with AutoGenerateColumns to true. I can double-click on the cell that I want to edit, and then I can edit the text that is in the cell.

But when I set AutoGenerateColumns to false and want to use a custom DataGridTextColumns , I can also double-click on the cell. But the text that was there is deleted, so I have an empty line instead of the one I wanted to edit a little.

Any ideas on this issue?

This is my DataGrid :

 <DataGrid ItemsSource="{Binding Tasks}" Margin="0,10,30,0" AutoGenerateColumns="False" Style="{DynamicResource DataGridStyle}" HorizontalScrollBarVisibility="Hidden" SelectedItem="{Binding SelectedTask}"> <DataGrid.Columns> <DataGridTextColumn> <DataGridTextColumn.ElementStyle> <Style TargetType="TextBlock"> <Setter Property="Margin" Value="6,0,0,0" /> <Setter Property="Text" Value="{Binding Description}" /> <Setter Property="VerticalAlignment" Value="Center" /> </Style> </DataGridTextColumn.ElementStyle> </DataGridTextColumn> </DataGrid.Columns> </DataGrid> 

Edit: I also noticed that when AutoGenerateColumns set to false, and when I insert a new row, the linked text does not get set ... And when I set AutoGeneratedColumns to true, it binds the inserted text.

+4
source share
1 answer

There was a datagrid column in the data grid, and this column has a CellTemplate and a CellEditingTemplate. If you define a template for both, you can explicitly set the binding for both. Perhaps this will solve your problem.

Here is an example template column with both templates

 <DataGridTemplateColumn Header="TEXT" > <DataGridTemplateColumn.CellTemplate> <DataTemplate> <TextBlock Text="{Binding YourBindingProperty}" Style="{StaticResource YourEditStyle}"/> </DataTemplate> </DataGridTemplateColumn.CellTemplate> <DataGridTemplateColumn.CellEditingTemplate> <DataTemplate> <TextBox x:Name="EditTextbox" Text="{Binding YourBindingProperty, Mode=TwoWay, UpdateSourceTrigger=LostFocus, ValidatesOnDataErrors=True}" Style="{StaticResource YourEditStyle}"> </DataTemplate> </DataGridTemplateColumn.CellEditingTemplate> </DataGridTemplateColumn> 

Hope this helps

+6
source

Source: https://habr.com/ru/post/1485880/


All Articles