Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

WPF Datagrid edit cell issue

Tags:

mvvm

wpf

datagrid

When I bind my ObservableCollection to my DataGrid with AutoGenerateColumns to true. I can double click on the cell 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 custom DataGridTextColumns, I can also double click the cell. But the text that was in there is removed so I have an empty string instead of the one I wanted to edit a little bit.

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 is set to false and when I insert a new row the binded text isn't getting set... And when I set AutoGeneratedColumns to true it binds the inserted text.

like image 358
koala Avatar asked Mar 24 '23 14:03

koala


1 Answers

The data grid had a datagrid template column and that column has a CellTemplate and a CellEditingTemplate. If you define the template for both you can explicitly set the binding for both as well. Maybe that will solve your problem.

here is sample of 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

like image 186
J King Avatar answered Apr 03 '23 04:04

J King