【发布时间】:2023-02-06 05:18:51
【问题描述】:
我开发了一些应用程序。而且我发现了一些与 DateTime 格式相关的奇怪事情。所以我创建了一些测试应用程序来更详细地检查它。 因此,我的测试应用程序具有以下结构:
-
只有 Date 属性的自定义对象类:
public class MyObject { public DateTime Date { get; private set; } public MyObject(DateTime date) { Date = date; } }-
自定义 ViewModel 类:
public class MyViewModel : INotifyPropertyChanged { public virtual ICollectionView TableView { get => tableView; set { tableView = value; OnPropertyChanged(nameof(TableView)); } } public virtual ObservableCollection<MyObject> TableItems { get { return tableItems; } set { tableItems = value; OnPropertyChanged(nameof(TableItems)); TableView = CollectionViewSource.GetDefaultView(tableItems); } } public MyViewModel() { var dateTimes = new List<MyObject>() { new MyObject(DateTime.MinValue), new MyObject(DateTime.Now), new MyObject(DateTime.MaxValue) }; TableItems = new ObservableCollection<MyObject>(dateTimes); } private ICollectionView tableView; private ObservableCollection<MyObject> tableItems; public event PropertyChangedEventHandler PropertyChanged; public void OnPropertyChanged([CallerMemberName] string prop = "") { if (PropertyChanged != null) PropertyChanged(this, new PropertyChangedEventArgs(prop)); } } -
使用 DataGrid 和 ListView 来查看控件。它们都绑定到同一个 TableView 集合:
<Grid> <Grid.RowDefinitions> <RowDefinition Height="300"/> <RowDefinition Height="300"/> </Grid.RowDefinitions> <DataGrid ItemsSource="{Binding TableView}"> </DataGrid> <ListView Grid.Row="1" ItemsSource="{Binding TableView}"> <ListView.ItemTemplate> <HierarchicalDataTemplate> <CheckBox HorizontalContentAlignment="Left" VerticalContentAlignment="Center"> <CheckBox.Content> <Label Content="{Binding Date}"/> </CheckBox.Content> </CheckBox> </HierarchicalDataTemplate> </ListView.ItemTemplate> </ListView> </Grid>
在这种情况下,我在表格和列表中看到了不同的日期视图:
如果我在 ListView 项目模板中将 Label 更改为 TextBlock,我将看到相同的结果:
为什么会这样?以及如何根据 Culture 日期时间设置在所有控件中显示相同的格式?
-
【问题讨论】:
-
日期从 1/1/01 开始,这是 MIN。由于您没有初始化 MIN,因此您得到的是 1/1/01。 MAX 也是如此,即 12/31/9999。要获得不同的格式,请使用 ToString("d/M/yyyy h:mm:ss tt")。