WPF dataGgridCell Edit Mode
-
09-06-2021 - |
Question
I have requirement to keep datagridcell always in edit mode. I dont find any option to make datagrid cell edit mode so I took TextBox under datagrid cell using control template.
I am able to write in text box but datagrid cell content never get updated. How I can update datagrid cell content with whatever I write in textbox ? Here is style :
<Style TargetType="{x:Type DataGridCell}" x:Key="DatagridCellWithTextbox">
<Setter Property="BorderThickness" Value="2"></Setter>
<Setter Property="Foreground" Value="{DynamicResource ContentNormalBrush}"/>
<Setter Property="Margin" Value="0"></Setter>
<Setter Property="VerticalContentAlignment" Value="Center"></Setter>
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type DataGridCell}">
<Grid Background="{TemplateBinding Background}">
<Border BorderBrush="{TemplateBinding BorderBrush}" BorderThickness="{TemplateBinding BorderThickness}" Background="{TemplateBinding Background}" SnapsToDevicePixels="True">
<TextBox x:Name="txtCell" Text="{Binding RelativeSource={RelativeSource TemplatedParent}, Path=Content.Text}" VerticalContentAlignment="Top" Focusable="True" />
</Border>
</Grid>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
Thanks Dee
La solution
Have you tried DataGridCell.IsEditing Property?
<Style TargetType="{x:Type DataGridCell}">
<Setter Property="IsEditing" Value="True" />
</Style>
Edit:
You can keep in edit mode setting Cancel
property in DataGrid.CellEditEnding Event to True
.
<DataGrid CellEditEnding="DataGrid_CellEditEnding"
.
private void DataGrid_CellEditEnding(object sender, DataGridCellEditEndingEventArgs e)
{
e.Cancel = true;
}
Autres conseils
I know this question is old but I've developed my own solution recently to this.
All I do is inherit from DataGridTextColumn
and override the GenerateElement
method:
public class EditingTextBoxColumn : DataGridTextColumn
{
protected override FrameworkElement GenerateElement(DataGridCell cell, object dataItem)
{
var textbox = base.GenerateEditingElement(cell, dataItem) as TextBox;
textbox.IsReadOnly = IsReadOnly;
return textbox;
}
}
This will work for other types of column aswell.
Of course, this only works for DataGridColumn
types that already exist (DataGridTextColumn
, DataGridComboBoxColumn
etc...).
I know this is old, but I think I have a better answer. Use a read-only DataGridTemplateColumn and set the CellTemplate. Bindings don't work properly in CellTemplate, but you can fix that with a different RelativeSource:
<DataGridTemplateColumn Width="Auto" Header="Select" IsReadOnly="True">
<DataGridTemplateColumn.CellTemplate>
<DataTemplate DataType="models:DealAcctListItem">
<CheckBox IsChecked="{Binding RelativeSource=
{RelativeSource AncestorType=DataGridCell},
Path=DataContext.IsSelected}" />
</DataTemplate>
</DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>
This is far easier than trying to get DataGrid's edit modes to work correctly.