How to show Persian date in WPF DataGrid?
How can I change this code (or somewhere else):
<DataGridTemplateColumn x:Name="timeColumn" Header="time" IsReadOnly="True">
<DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<DatePicker SelectedDate="{Binding time, Mode=TwoWay, NotifyOnValidationError=true, ValidatesOnExceptions=true}"/>
</DataTemplate>
</DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>
Show date in Persian format? the time in the database is in Timestamp format. I just want to "show it" in Persian format and have a Persian calendar if possible.
source to share
If you want to show PersianDateTime
, you can use System.Globalization.PersianCalendar
in your view model like this:
public string PersianDate
{
get
{
PersianCalendar pc = new PersianCalendar();
DateTime thisDate = convert your Timestamp to DateTime here ...;
return string.Format("{0}, {1}/{2}/{3} {4}:{5}:{6}",
pc.GetDayOfWeek(thisDate),
pc.GetMonth(thisDate),
pc.GetDayOfMonth(thisDate),
pc.GetYear(thisDate),
pc.GetHour(thisDate),
pc.GetMinute(thisDate),
pc.GetSecond(thisDate));
}
}
And then in your Xaml:
<DataGrid ItemsSource="{Binding YourList}" AutoGenerateColumns="False">
<DataGrid.Columns>
<DataGridTextColumn Header="PersianTime" Binding="{Binding PersianDate}"/>
< Other columns ... />
</DataGrid.Columns>
</DataGrid>
If you need Farsi format Persian calendar and language you can check this library , another good source this link is from code project.
source to share
For me, changing the environment to change the DatePicker format (like Thread.CurrentCulture) is not a good idea. Of course, you can create a Control derived from a DatePicker and implement a dependency property like Format, but that takes too much effort. The simple and elegant solution I found is a required value not for the SelectedDate itself, but for some unused property (I used the ToolTip property for that) and updated this property when the SelectedDate was changed. C # implementation for one-way binding looks like this:
DatePicker datePicker = new DatePicker();
datePicker.SetBinding(ToolTipProperty, "Date");
datePicker.SelectedDateChanged += (s, ea) =>
{
DateTime? date = datePicker.SelectedDate;
string value = date != null ? date.Value.ToString("yyyy-MM-dd") : null;
datePicker.ToolTip = value;
};
XAML + C # should look like this:
XAML:
<DatePicker ToolTip="{Binding Date Mode=TwoWay}"
SelectedDateChanged="DatePicker_SelectedDateChanged"/>
FROM#
private void DatePicker_SelectedDateChanged(object sender, EventArgs ea)
{
DatePicker datePicker = (DatePicker)sender;
DateTime? date = datePicker.SelectedDate;
string value = date != null ? date.Value.ToString("yyyy-MM-dd") : null;
datePicker.ToolTip = value;
}
For a two-way implementation, handle the ToolTipChanged event in the same way to update the SelectedDate.
</Setter>
</Style>
</DatePicker.Resources>
</DataTemplate>
</DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>
source to share