Carl R
Carl R

Reputation: 8214

Windows Phone 7 dates not internationalized?

I have an app where resources are pulled up localized correctly. However, databinding a datetime always shows using en-US formatting.

I checked in the App class during startup, and both CurrentCulture and CurrentUICulture are set to the expected culture.

I have no date formatting applied as far as I know.

How should I get the dates formatted with the current culture?

Upvotes: 4

Views: 114

Answers (3)

Carl R
Carl R

Reputation: 8214

Turns out there's a very simple solution.

By adding a IValueConverter and using the converter in the binding expression, but ignoring the culture argument, the formatting works perfectly.
You will need one converter (if you don't make it take arguments) for each different format.

Converter (removed the attribute from the sample):

public class DateConverter : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
    {
        DateTime date = (DateTime)value;
        return date.ToShortDateString();
    }

    public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
    {
        string strValue = value as string;
        DateTime resultDateTime;
        if (DateTime.TryParse(strValue, out resultDateTime))
        {
            return resultDateTime;
        }
        return DependencyProperty.UnsetValue;
    }
}

namespace

xmlns:conv="clr-namespace:Sjofartsverket.LotsPDA20.Client.Converters"

resource

<conv:DateConverter x:Key="dateConverter" />

Binding expression:

<TextBlock Text="{Binding StartDate, Converter={StaticResource dateConverter}}" 

Result: The date is rendered in the correct culture.

Upvotes: 1

Alex Filipovici
Alex Filipovici

Reputation: 32541

You have to change the data type of the property StartDate to string:

string _startDate;
public string StartDate
{
    get { return _startDate; }
    set
    {
        _startDate = value;
        OnPropertyChanged("StartDate");
    }
}

When you assign the value to the StartDate, use one of the following overloads of the ToString() method, upon convenience:

StartDate = DateTime.Now.ToString();
StartDate = DateTime.Now.ToString("d");
StartDate = DateTime.Now.ToString("D");

Upvotes: 1

Matt Lacey
Matt Lacey

Reputation: 65564

Rather than pass the DateTime to the view and rely on the binding to convert it to the correct format, create an additional property that wraps the existing one but applies the appropriate conversion/formatting.
e.g.

public class MyViewModel
{
    public DateTime StartDate { get; set; }

    public string LocalizedStartDate
    {
        get
        {
            return this.StartDate.ToString(CultureInfo.CurrentUICulture);
        }
    }
}

and then bind:

<TextBlock Text="{Binding LocalizedStartDate}" .... />

Upvotes: 1

Related Questions