Need to format dates in dynamically built WPF DataGrid

后端 未结 8 579
眼角桃花
眼角桃花 2020-12-05 09:51

We are binding an unknown result set to a WPF DataGrid at run time. Some of our columns are going to contain DateTime values and we need to properly format these date time

相关标签:
8条回答
  • 2020-12-05 10:23

    I figured out how to do this in code...hopefully there is a way to mimic this in XAML. (Please post if you find a working XAML sample.)

    To accomplish this in code, add an event handler for the Grid's AutoGeneratingColumn event, such as:

    private void ResultsDataGrid_AutoGeneratingColumn(object sender, DataGridAutoGeneratingColumnEventArgs e)
    {
        if (e.PropertyType == typeof(DateTime))
        {
            DataGridTextColumn dataGridTextColumn = e.Column as DataGridTextColumn;
            if (dataGridTextColumn != null)
            {
                dataGridTextColumn.Binding.StringFormat = "{0:d}";
            }
        }
    }
    
    0 讨论(0)
  • 2020-12-05 10:26
    <DataGridTextColumn Header="Last update"
        Width="110"
        IsReadOnly="True"
        Binding="{Binding Path=Contact.TimeUpdate, StringFormat={}\{0:dd/MM/yyyy hh:mm\}, Mode=OneWay}" />
    
    0 讨论(0)
  • 2020-12-05 10:29

    i run this way. its work complete .

    <TextBlock  Text="{Binding Date_start,  StringFormat=\{0:dd-MM-yyyy\}, Mode=OneWay}" />
    
    0 讨论(0)
  • 2020-12-05 10:31

    Hey you can set the locale culture info in the constructor of the WPF form as

    this.Language = XmlLanguage.GetLanguage(CultureInfo.CurrentCulture.IetfLanguageTag);

    Or you can include the xml markup xml:lang="en-GB" in the window header markup

    0 讨论(0)
  • 2020-12-05 10:39

    The answer of FarrEver, May 11 is good, but by me it doens't function. i still get American mm/dd/yyy instead my German dd/mm/yyyy. So I propose to find the regional settings of computer and use it in StringFormat

        Private Sub DGrid_AutoGeneratingColumn(ByVal sender As System.Object, ByVal e As Microsoft.Windows.Controls.DataGridAutoGeneratingColumnEventArgs)
        If e.PropertyType Is GetType(DateTime) Then
            Dim dataGridTextColumn As DataGridTextColumn = TryCast(e.Column, DataGridTextColumn)
            If dataGridTextColumn IsNot Nothing Then
                Dim ShortDatePattern As String = System.Globalization.DateTimeFormatInfo.CurrentInfo.ShortDatePattern
                dataGridTextColumn.Binding.StringFormat = "{0:" + ShortDatePattern + "}" '"{0:dd/MM/yyyy}"
            End If
        End If
    End Sub
    

    see also: my blog

    0 讨论(0)
  • 2020-12-05 10:45

    Format the binding by StringFormat:

    <DataGridTextColumn Header="Fecha Entrada" 
                        Width="110"  
                        Binding="{Binding EnterDate, StringFormat={}\{0:dd/MM/yyyy hh:mm\}}"
                        IsReadOnly="True" />
    

    I think it's better than writing code behind pieces of code

    0 讨论(0)
提交回复
热议问题