Question

Based on a setting in my application I need to be able to show different formats of showing a Date in XAML. For example it needs to be either in "yyyy/MM/dd" format or in "MM/dd/yyyy" format.

What are some ways that I can achieve this? Please note that the places in my application that I need to handle this are limited so even a "fix on the spot" type of solution would work in my case too.

Thanks for suggestions.

Was it helpful?

Solution

You can use a ValueConverter for this. Just replace YourApplicationSettings.YearFirst with wherever you're pulling the setting from.

public class DateTime2FlexibleDateString : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
    {
        var dt = value as DateTime?
        if (dt== null)
        {
            return null;
        }

        var dateTime = dt.Value;

        if (YourApplicationSettings.YearFirst)
        {
            return dateTime.ToString("yyyy/MM/dd");
        }

        return dateTime.ToString("MM/dd/yyyy");
    }

    public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
    {
        return null;
    }
}

Then either in each xaml file that needs it, or in a App.xaml (or a resource dictionary added to App.xaml), add a static resource for your converter.

<UserControl.Resources>
    <converters:DateTime2FlexibleDateString x:Key="DateTime2FlexibleDateString" />
</UserControl.Resources>

And then when you bind to the date, specify the converter.

<TextBlock Text="{Binding MyDateTimeVariable, Converter={StaticResource DateTime2FlexibleDateString}" />

OTHER TIPS

It depends on the context of what you are doing, but if you are binding to a DateTime then you can alter the StringFormat property like so:

<TextBlock Text="{Binding MyDateTimeVariable, StringFormat='yyyy/MM/dd'}" />
<TextBlock Text="{Binding MyDateTimeVariable, StringFormat='MM/dd/yyyy'}" />

Here is a good example of some different format options that be achieved like this.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top