Search code examples
c#wpfdata-bindingconvertersivalueconverter

WPF Datagrid: Editing values via UI that have been converted using ValueConverter


I have a datagrid with a column "Total Amount". This is a double type and is converted by a IValueConverter to a currency type with the "$" symbol and commas.

(1) But the cell needs to be editable so the user can make changes to the row including the amount. How do I do this? Right now, editing freezes the application (not surprised) as I have no clue how to handle this.

(2) If the user adds a new row and adds a new item to it. How do I prefix the value with a $ symbol and add the commas in relevant places as the user types?

Note: One workaround is I guess to have the TotalAmount property as a string itself and convert to double when I need to perform any operation. Also add a validation to ensure user inputs a double type. But I still don't know how to implement point #2.


Solution

  • Key here is using the CellTemplate & CellEditingTemplate

    Thanks to - Link1 & Link2

    My Solution was the combination of the above two as -

    <DataGridTemplateColumn Header="Total Amount">
        <DataGridTemplateColumn.CellTemplate>
            <DataTemplate>
                <TextBlock Text="{Binding Path=TotalAmount, Converter={StaticResource CurrencyConverter}}"/>
            </DataTemplate>
        </DataGridTemplateColumn.CellTemplate>
        <DataGridTemplateColumn.CellEditingTemplate>
            <DataTemplate>
                <TextBox Text="{Binding Path=TotalAmount, StringFormat=\{0:N2\},UpdateSourceTrigger=PropertyChanged, Mode=TwoWay}"/>
            </DataTemplate>
        </DataGridTemplateColumn.CellEditingTemplate>
    </DataGridTemplateColumn>