如何设置绑定stringformat到所有DataGridTextColumn控件?

Jat*_*ing 2 wpf string-formatting datagridtextcolumn

这是我的DataGridTextColumn控件之一,如下所示:

<DataGridTextColumn x:Name="contractStartDateColumn" Header="Start Date" Binding="{Binding Path=StartDate, StringFormat={}\{0:dd/MM/yyyy\}}" />
Run Code Online (Sandbox Code Playgroud)

那么如何将StringFormat = {} {0:dd/MM/yyyy}设置为所有DataGridTextColumn控件而不是设置每一个?

ice*_*bat 5

您可以创建自定义绑定类来设置StringFormat和使用它来绑定值:

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

在XAML中:

<DataGrid AutoGenerateColumns="False" ItemsSource="{Binding TimeList}">
    <DataGrid.Columns>
        <DataGridTextColumn Binding="{local:CustomBinding StartDate}" />
    </DataGrid.Columns>
</DataGrid>
Run Code Online (Sandbox Code Playgroud)