Search code examples
wpfdatagridcelldatatemplate

Change of WPF Datagrid Cell's DataTemplate caused not desired result


I have a WPF DataGrid, And I have modified it's first column's cell templete as shown below:

<DataGridTemplateColumn.CellTemplate>
                    <DataTemplate>
                        <Grid Margin="0">
                            <Grid.ColumnDefinitions>
                                <ColumnDefinition Width="*"/>
                                <ColumnDefinition Width="20"/>
                            </Grid.ColumnDefinitions>
                            <TextBox Grid.Column="0" Text="{Binding W_NAME, Mode=TwoWay}" 
                                     BorderThickness="0" 
                                     Background="Transparent"/>
                            <Button Grid.Column="1" Width="20"  
                                    Background="Transparent"
                                    IsEnabled="{Binding CantFound}"
                                    HorizontalAlignment="Right">
                                <StackPanel>
                                    <Image Source="/Resources/Pictures/Search.png"/>
                                </StackPanel>
                            </Button>
                        </Grid>
                    </DataTemplate>
                </DataGridTemplateColumn.CellTemplate>

I have also the second "ordinary" {not modified} column, called ID (type of int).

Not desired result appears as shown below:

step 1: I open the user control where my datagrid is:

enter image description here

step 2: I click the first cell to write something in it (For some reason, it is enough only one click to put cursor in it. An "ordinary" cell needs 2 - one for focus and one - to put cursor in it)

enter image description here

step 3: I write something in it (this cell is still focused)

enter image description here

step 4: I click for the first time the second cell (And it gets focus only).

enter image description here

step 5: I click one more time the second cell (cursor is there and default value is written automatically). at this point value in first cell is dissapeared.

enter image description here

step 6: I write my value in the second cell:

enter image description here

step 7: I press the enter button on my keyboard and this happens

enter image description here

Maybe the reason of it is relatively simple, but I fount it difficult to describe it well only with words.


Solution

  • The CellTemplate of the column is supposed to include a read-only TextBlock. You should put the editable TextBox in the CellEditingTemplate.

    That's how the built-in DataGridTextColumn works. You see a TextBlock by default and when you double-click on the cell to enter the edit mode, a TextBox appears. The Text property of the TextBlock and the Text property of the TextBox are bound to the same source property.