WPF数据网格中的日期格式

本文关键字:日期 格式 网格 数据 数据网 WPF | 更新日期: 2023-09-27 18:12:59

我要更改的是日期列的格式"DD/MM/YYYY HH:MM:SS";DD.MM.YYYY" .

  <DataGrid Name="dgBuchung" AutoGenerateColumns="True" 
            ItemsSource="{Binding}" Grid.ColumnSpan="3" >
  <ab:DataGridTextColumn Header="Fecha Entrada" Width="110"  
       Binding="{Binding date, StringFormat={}{0:dd/MM/yyyy}}" IsReadOnly="True" />
                        
</DataGrid>
                                      

不幸的是,代码抛出了一个XMLParseException

首先,这种方式的解决方案是可能的,而使用AutoGenerateColumns?如果不是,我还能怎么处理呢?

如果是,上面的代码有什么问题?

WPF数据网格中的日期格式

不要忘记使用DataGrid。列,所有列都必须在该集合内。在我的项目中,我对日期的格式略有不同:

<tk:DataGrid>
    <tk:DataGrid.Columns>
        <tk:DataGridTextColumn Binding="{Binding StartDate, StringFormat='{0:dd.MM.yy HH:mm:ss'}}" />
    </tk:DataGrid.Columns>
</tk:DataGrid>

使用AutoGenerateColumns,您将无法控制格式,因为DataGird将添加自己的列。

来得太晚了,但万一有人偶然发现这个页面…

可以通过在XAML中设置AutoGeneratingColumn处理程序来实现:

<DataGrid AutoGeneratingColumn="OnAutoGeneratingColumn"  ..etc.. />

然后在后面的代码中这样做:

private void OnAutoGeneratingColumn(object sender, DataGridAutoGeneratingColumnEventArgs e)
{
    if (e.PropertyType == typeof(System.DateTime))
        (e.Column as DataGridTextColumn).Binding.StringFormat = "dd/MM/yyyy";
}

如果你的绑定属性是DateTime,那么你所需要做的就是

Binding={Property, StringFormat=d}
Binding="{Binding YourColumn ,StringFormat='yyyy-MM-dd'}"

首先选择datagrid,然后转到属性找到Datagrid_AutoGeneratingColumn并双击然后使用这个代码

   Datagrid_AutoGeneratingColumn(object sender, DataGridAutoGeneratingColumnEventArgs e)
            {
                if (e.PropertyName == "Your column name")
                    (e.Column as DataGridTextColumn).Binding.StringFormat = "dd/MMMMMMMMM/yyyy";
                if (e.PropertyName == "Your column name")
                    (e.Column as DataGridTextColumn).Binding.StringFormat = "dd/MMMMMMMMM/yyyy";
            }

我试了一下,它可以在WPF上工作

我知道公认的答案是相当旧的,但是有一种方法来控制AutoGeneratColumns的格式:

首先创建一个函数,在生成列时触发:

<DataGrid x:Name="dataGrid" AutoGeneratedColumns="dataGrid_AutoGeneratedColumns" Margin="116,62,10,10"/>

然后检查所生成的列的类型是否为DateTime,并将其字符串格式更改为"d"以删除时间部分:

private void DataGrid_AutoGeneratingColumn(object sender, DataGridAutoGeneratingColumnEventArgs e)
        {
            if(YourColumn == typeof(DateTime))
            {
                e.Column.ClipboardContentBinding.StringFormat = "d";
            }
        }

这是一个非常古老的问题,但我找到了一个新的解决方案,所以我写了下来。

首先,这种方式的解决方案是可能的,而使用AutoGenerateColumns?

是的,这可以用AttachedProperty来完成,如下所示。

<DataGrid AutoGenerateColumns="True" 
   local:DataGridOperation.DateTimeFormatAutoGenerate="yy-MM-dd"
   ItemsSource="{Binding}" />

AttachedProperty

定义了两个AttachedProperty,允许您指定两种格式。DateTimeDateTimeFormatAutoGenerate, TimeSpanTimeSpanFormatAutoGenerate

class DataGridOperation
{
    public static string GetDateTimeFormatAutoGenerate(DependencyObject obj) => (string)obj.GetValue(DateTimeFormatAutoGenerateProperty);
    public static void SetDateTimeFormatAutoGenerate(DependencyObject obj, string value) => obj.SetValue(DateTimeFormatAutoGenerateProperty, value);
    public static readonly DependencyProperty DateTimeFormatAutoGenerateProperty =
        DependencyProperty.RegisterAttached("DateTimeFormatAutoGenerate", typeof(string), typeof(DataGridOperation),
            new PropertyMetadata(null, (d, e) => AddEventHandlerOnGenerating<DateTime>(d, e)));
    public static string GetTimeSpanFormatAutoGenerate(DependencyObject obj) => (string)obj.GetValue(TimeSpanFormatAutoGenerateProperty);
    public static void SetTimeSpanFormatAutoGenerate(DependencyObject obj, string value) => obj.SetValue(TimeSpanFormatAutoGenerateProperty, value);
    public static readonly DependencyProperty TimeSpanFormatAutoGenerateProperty =
        DependencyProperty.RegisterAttached("TimeSpanFormatAutoGenerate", typeof(string), typeof(DataGridOperation),
            new PropertyMetadata(null, (d, e) => AddEventHandlerOnGenerating<TimeSpan>(d, e)));
    private static void AddEventHandlerOnGenerating<T>(DependencyObject d, DependencyPropertyChangedEventArgs e)
    {
        if (!(d is DataGrid dGrid))
            return;
        if ((e.NewValue is string format))
            dGrid.AutoGeneratingColumn += (o, e) => AddFormat_OnGenerating<T>(e, format);
    }
    private static void AddFormat_OnGenerating<T>(DataGridAutoGeneratingColumnEventArgs e, string format)
    {
        if (e.PropertyType == typeof(T))
            (e.Column as DataGridTextColumn).Binding.StringFormat = format;
    }
}

如何使用

<

视图/h3>
<Window
   x:Class="DataGridAutogenerateCustom.MainWindow"
   xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
   xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
   xmlns:local="clr-namespace:DataGridAutogenerateCustom"
   Width="400" Height="250">
   <Window.DataContext>
      <local:MainWindowViewModel />
   </Window.DataContext>
   <StackPanel>
      <TextBlock Text="DEFAULT FORMAT" />
      <DataGrid ItemsSource="{Binding Dates}" />
      <TextBlock Margin="0,30,0,0" Text="CUSTOM FORMAT" />
      <DataGrid
         local:DataGridOperation.DateTimeFormatAutoGenerate="yy-MM-dd"
         local:DataGridOperation.TimeSpanFormatAutoGenerate="dd'-hh'-mm'-ss"
         ItemsSource="{Binding Dates}" />
   </StackPanel>
</Window>

ViewModel

public class MainWindowViewModel
{
    public DatePairs[] Dates { get; } = new DatePairs[]
    {
        new (){StartDate= new (2011,1,1), EndDate= new (2011,2,1) },
        new (){StartDate= new (2020,1,1), EndDate= new (2021,1,1) },
    };
}
public class DatePairs
{
    public DateTime StartDate { get; set; }
    public DateTime EndDate { get; set; }
    public TimeSpan Span => EndDate - StartDate;
}

demo_wpf_datagrid