how to set binding stringformat to all DataGridTextColumn controls?

筅森魡賤 提交于 2020-01-14 15:56:30

问题


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 ?


回答1:


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>



回答2:


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


来源:https://stackoverflow.com/questions/8290921/how-to-set-binding-stringformat-to-all-datagridtextcolumn-controls

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!