简体   繁体   中英

how to set binding stringformat to all DataGridTextColumn controls?

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 ?

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>

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}}" />

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM