Number format in a DataGrid Cell

Apr 21, 2009 at 4:06 PM

I would like to know how can i have a number formatted in a cell of a datagrid when i'm not in edit mode and not formated when i'm in edit mode.

Is it possible to do with a DataGridTextColumn or i need to define a DatagridTemplateColumn ?

If is possible with a DatagridTextColumn could you show me an example please.

Thank you.

Rui G.
Apr 21, 2009 at 6:01 PM
Hi RuiG

Every non-template column (text, combo, check box and hyperlink) has 2 styles

ElementStyle - Style that applies to the cell visual control when it not in edit mode (Mostly a Text Block)
and EditElementStyle - Style that applies to the editable control of the cell (in your case the Text Box)

Suppose you have numeric property (say Salary with value 500) bound to the text column that binds directly with the Binding={Binding Path=Salary} attribute. So in editing mode TextBox would show unformatted 500 number.

As you want Salary to appear differently in non-edit ElementStyle what you should do in XAML is in ElementStyle open a Style tag and specify a setter for the relevant property (e.g. Text) and in the Value attribute provide binding via a converter that formats the Salary to the respective unit string (suppose $500.00}.

Something like this (syntax might not be exactly correct)

    <Style TargetType={x:Type TextBlock}>
        <Setter Property="Text" Value="{Binding Path=Salary, Converter=Local_SalaryToStringConverter}"/>

    <Style TargetType={x:Type TextBox}>
            <Setter Property="Text" Value="{Binding Path=Salary}"/>

Vinit Sankhe.

Apr 21, 2009 at 7:41 PM
Hi Vinit Sankhe,

Thank you for your reply it was very helpful.

What i have done was the following:

                                <Style TargetType="{x:Type TextBlock}">
                                    <Setter Property="Text" Value="{Binding Path=Sal,StringFormat=$ \{0:N2\}}"/>
                                    <Setter Property="TextAlignment" Value="Right"/>
                                <Style TargetType="{x:Type TextBox}">
                                    <Setter Property="Text" Value="{Binding Path=Sal}"/>

and it is working like i expect.

Thank you.