How to apply String formatting in DataGrid – WPF

Question:

I have a Data Grid in WPF that has CPF, RG, CEP and others columns, I need to format it to:

CPF: 111,111,111-11

ID: 11.111.11-1 With number at the end

RG: 11.111.111-A With letter at the end

CEP: 11111-11

It just fills in the data and doesn't format.

<Window x:Class="ProjSistema.Wpf.Cadastro.Teste"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Title="Teste" Height="300" Width="300">
<Grid>
    <DataGrid  Name="dtgTeste" AutoGenerateColumns="False">
        <DataGrid.Columns>
            <DataGridTextColumn Header="CPF" MinWidth="100" Binding="  {Binding CPF, StringFormat={}{0:###.###.###-##}}"/>
            <DataGridTextColumn Header="RG" MinWidth="100" Binding="{Binding RG, StringFormat={}{0:##.###.###-#}}" />
            <DataGridTextColumn Header="CEP" MinWidth="100" Binding="{Binding CEP, StringFormat={}{0:#####-##}}" />
        </DataGrid.Columns>
    </DataGrid>
</Grid>

public partial class Teste : Window
{
    public Teste()
    {
        InitializeComponent();

        List<PropriedadeTeste> lstTeste = new List<PropriedadeTeste>();
        PropriedadeTeste propTeste = new PropriedadeTeste();
        propTeste.CPF = "11111111111";
        propTeste.RG = "111111111";
        propTeste.CEP = "11111111";
        lstTeste.Add(propTeste);
        dtgTeste.ItemsSource = lstTeste;
    }
}

Answer:

You can apply the StringFormat to Binding like this:

<DataGrid  Name="dtgTeste" AutoGenerateColumns="False">
    <DataGrid.Columns>
        <DataGridTextColumn Header="CPF" Binding="{Binding CPF, StringFormat={}{0:###.###.###-##}}"/>
        <DataGridTextColumn Header="RG" Binding="{Binding RG, StringFormat={}{0:##.###.###-#}}" />
        <DataGridTextColumn Header="CEP" Binding="{Binding CEP, StringFormat={}{0:#####-##}}" />
    </DataGrid.Columns>
</DataGrid>

There are also other methods creating a custom class to do the formatting.

Scroll to Top