【问题标题】:DateTime region specific formatting in WPF ListViewWPF ListView 中的日期时间区域特定格式
【发布时间】:2010-01-02 22:10:57
【问题描述】:

在 WPF 应用程序中,我有一个 ListView:

<ListView Height="100" Width="434" Margin="0,2,0,0" x:Name="lvItems" ItemsSource="{Binding ElementName=MainWindow, Path=ShowQuCollection}" >
  <ListView.View>
    <GridView>
     <GridViewColumn Header="Date" Width="100" DisplayMemberBinding="{Binding Date}"/>
     <GridViewColumn Header="Time" Width="100" DisplayMemberBinding="{Binding Time}"/>
     <GridViewColumn Header="Description" Width="200" DisplayMemberBinding="{Binding Description}"/>
    </GridView>
   </ListView.View>
 </ListView>

通过数据绑定与 ObservableCollection 连接。 ObservableCollection 是使用 LINQ to SQL 从 SQLServer db 表填充的。

ObservableCollection<ShowsQu> _ShowQuCollection =
        new ObservableCollection<ShowsQu>();

public ObservableCollection<ShowsQu> ShowQuCollection
{ get { return _ShowQuCollection; } }

public class ShowsQu
{
    public string ShowCode { get; set; }
    public DateTime Date { get; set; }
    public TimeSpan Time { get; set; }
    public string Description { get; set; }
}

private void VisualizeAllShows()
{

    MyfirstdbDataContext context = new MyfirstdbDataContext();
    _ShowQuCollection.Clear();

    var sh = from p in context.Shows select p;

    foreach (var p in sh)  
      _ShowCollection.Add(new ShowsQu
        {
            Date = p.Date,
            Time = p.Time,
            Description = p.Description
        });                 
}

问题在于 ListView 按原样显示 SQLServer 数据库表中的日期字段 - 没有应用特定于区域的格式(我猜它应该默认应用)。

我应该在哪里以及如何将其格式化为 PC 区域设置的格式?

【问题讨论】:

    标签: c# wpf linq-to-sql data-binding listview


    【解决方案1】:

    由于某种原因,WPF 不会自动选择当前的文化,您必须自己设置。一个简单的方法是在您的应用程序启动事件中添加以下代码:

    using System.Windows;
    using System.Windows.Markup;
    using System.Globalization;
    
    ...
    
    void App_Startup(object sender, StartupEventArgs e)
    {
    
        FrameworkElement.LanguageProperty.OverrideMetadata(  
            typeof(FrameworkElement),  
            new FrameworkPropertyMetadata(XmlLanguage.GetLanguage(CultureInfo.CurrentCulture.IetfLanguageTag)));
    }
    

    【讨论】:

    • 我避开了其他几个搜索结果,因为我认为这不是我的解决方案,因为日期格式错误的唯一地方是 ListView / GridViewColumn。然而,这'''是'''解决方案。请有人解释一下。 DatePicker,DateTimePicker,在我的文化中都没有这个,但不是 ListView。谢谢
    【解决方案2】:

    来自 MSDN:

    You can pass a CultureInfo object representing the culture whose formatting is to be used to a method that has an IFormatProvider parameter. The following example displays a date using the short date format of the pt-BR culture.
    

    从这里:http://msdn.microsoft.com/en-us/library/az4se3k1.aspx

    更多信息在这里:http://msdn.microsoft.com/en-us/library/5hh873ya.aspx

    希望这会有所帮助。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-11-06
      • 2014-12-15
      • 1970-01-01
      • 2019-10-01
      • 1970-01-01
      • 1970-01-01
      • 2021-08-21
      相关资源
      最近更新 更多