how to set binding stringformat to all DataGridTextColumn controls?
Asked Answered
H

2

4

This is one of my DataGridTextColumn controls looks like :

<DataGridTextColumn x:Name="contractStartDateColumn" Header="Start Date" Binding="{Binding Path=StartDate, StringFormat={}\{0:dd/MM/yyyy\}}" />

Then how can I set StringFormat={}{0:dd/MM/yyyy} to all of DataGridTextColumn controls instead of setting every single one ?

Holdover answered 28/11, 2011 at 2:33 Comment(0)
S
6

You can create custom binding class that sets StringFormat and use it to bind values:

public class CustomBinding : Binding
{
    public CustomBinding(string path) : base(path)
    {
        this.StringFormat = @"{0:dd/MM/yyyy}";
    }
}

And in XAML:

<DataGrid AutoGenerateColumns="False" ItemsSource="{Binding TimeList}">
    <DataGrid.Columns>
        <DataGridTextColumn Binding="{local:CustomBinding StartDate}" />
    </DataGrid.Columns>
</DataGrid>
Snowman answered 28/11, 2011 at 7:13 Comment(2)
when I try this my column is empty.Ortiz
nevermind my namespace was missing from the class. +1 thanksOrtiz
E
3

You can store StringFormat in a constant in .cs file; and in xaml use following

<DataGridTextColumn x:Name="contractStartDateColumn" Header="Start Date" Binding="{Binding Path=StartDate, StringFormat={x:static MyNamespace:MyClass.MyDateFormat}}" />
Erleena answered 28/11, 2011 at 12:36 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.