Search code examples
c#wpfdatagridwpfdatagrid

WPF DataGrid: Displaying 2 decimal places when not editing, but full number when editing


im am trying to have a datagrid, where when the user enters the value and presses enter, it displays the data with 2 decimal points of precision.

However when they click in to edit it, i want them to be able to view the whole number again.

What i currently have is:

<DataGridTextColumn Header="s" Binding="{Binding s, StringFormat=N2}" ElementStyle="{StaticResource TextColumnWhite}" >
    <DataGridTextColumn.EditingElementStyle>
        <Style TargetType="{x:Type TextBox}">
            <Setter Property="Text" Value="{Binding s}" />
            <Setter Property="Background" Value="Red" />
        </Style>
    </DataGridTextColumn.EditingElementStyle>
</DataGridTextColumn>

The red background is displaying for the datagrid cell but the number inside is not updating to the non formatted value.

Thanks for any help


Solution

  • You need to take away the string format at the parent level (which is overriding the EditingElementStyle) - and instead set the string format for the binding expression only in the styles for EditingElementStyle - but also for the regular ElementStyle (non-editing mode) which is a TextBlock style:

    <DataGridTextColumn Header="s" ElementStyle="{StaticResource TextColumnWhite}">
    
        <!-- editing view -->
        <DataGridTextColumn.EditingElementStyle>
            <Style TargetType="{x:Type TextBox}">
                <Setter Property="Text" Value="{Binding s}" />                            
                <Setter Property="Background" Value="Red" />
            </Style>                        
        </DataGridTextColumn.EditingElementStyle>
    
        <!-- not editing view -->
        <DataGridTextColumn.ElementStyle>
            <Style TargetType="{x:Type TextBlock}">
                <Setter Property="Text" Value="{Binding s, StringFormat=N2}" />
                <Setter Property="Background" Value="Transparent" />
            </Style>
        </DataGridTextColumn.ElementStyle>
    
    </DataGridTextColumn>