DateTime region specific formatting in WPF ListView
In WPF app I have a 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>
which is connected with ObservableCollection through databinding. ObservableCollection is populated from SQLServer db table using LINQ to SQL.
ObservableCollection<ShowsQu> _ShowQuCollection =
开发者_JS百科 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
});
}
The problem is that ListView displays a Date field from SQLServer database table as it is - without applying region specific formatting (I guessed it should be applied by default).
Where and what should I do to get it be formatted the way as PC regions settings are?
For some reason, WPF doesn't automatically pick up the current culture, you have to set it yourself. An easy way to do it is to add the following code in your application Startup event :
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)));
}
From 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.
From here: http://msdn.microsoft.com/en-us/library/az4se3k1.aspx
Some more info here: http://msdn.microsoft.com/en-us/library/5hh873ya.aspx
Hope this helps.
精彩评论