WPF: How to bind a numeric property to DataGridTextColumn?

9.7k Views Asked by At

I thought it should be a simple thing for WPF, but I can't make it work... I have an int property (Divisions) on my class and I want to bind it to a DataGrid column.

<DataGrid AutoGenerateColumns="False">
    <DataGrid.Columns>
            <DataGridTextColumn Header="Number of Divisions" Binding="{Binding Path=Divisions, StringFormat={}\{0:N0\}}" IsReadOnly="True"/>                
    </DataGrid.Columns>
</DataGrid>

However, it doesn't show up. I also tried this code and it doesn't work for me either:

<DataGrid AutoGenerateColumns="False">
    <DataGrid.Columns>
        <DataGridTemplateColumn Header="Divisions" IsReadOnly="True">
            <DataGridTemplateColumn.CellTemplate>
                <DataTemplate>
                    <TextBlock Text="{Binding Path=Divisions, StringFormat=C}" />
                </DataTemplate>
            </DataGridTemplateColumn.CellTemplate>
        </DataGridTemplateColumn>
    </DataGrid.Columns>
</DataGrid>

For testing purpse, if I add a string property to this class to return string value of Divisions, it just works fine. So, what's wrong here?

2

There are 2 best solutions below

2
On

Interesting... I was able to get things to work easily using the following (in VS 2010, .NET 4) example.

My Grid Definition:

<DataGrid ItemsSource="{Binding}" AutoGenerateColumns="False">
    <DataGrid.Columns>
        <DataGridTextColumn Header="Number of Divisions" 
                            Binding="{Binding Path=Divisions,  StringFormat={}\{0:N0\}}" 
                            IsReadOnly="True"/>
    </DataGrid.Columns>
</DataGrid>

Setting the Data Context:

this.DataContext = new List<MyItem>() { 
    new MyItem() { Divisions = 1 },
    new MyItem() { Divisions = 2 },
    new MyItem() { Divisions = 3 },
    new MyItem() { Divisions = 4 },
    new MyItem() { Divisions = 5 }
};

My Data Class Definition:

public class MyItem {
    public int Divisions { get; set; } 
}

Hope this helps!

2
On

I don't believe you're specifying your StringFormats correctly.

In the first example, try dropping the escape characters, like so: StringFormat={}{0:N0}

In the second: StringFormat={}{0:C}