Search code examples
c#wpfxamlglobalization

Why can't I use CultureInfo.CurrentCulture in XAML at design time?


I have the following XAML:

<TextBlock Text="{Binding Source={x:Static s:DateTime.Now}, StringFormat=Date: {0:dddd, MMMM dd}}"/>

s:DateTime.Now with xmlns:s="clr-namespace:System;assembly=mscorlib" works fine at runtime as well as in design mode (Visual Studio 2015 Enterprise).

But if I try the same with CultureInfo.CurrentCulture, then this works at runtime only and gives me an error in design mode (xmlns:c="clr-namespace:System.Globalization;assembly=mscorlib"):

<TextBlock Text="{Binding Source={x:Static s:DateTime.Now}, ConverterCulture={x:Static c:CultureInfo.CurrentCulture}, StringFormat=Date: {0:dddd, MMMM dd}}"/>

I'm not looking for a workaround. I am only trying to understand the difference between DateTime.Now and CultureInfo.CurrentCulture and why one of them works and the other one doesn't.


Solution

  • I know you did not ask for a workaround and I cannot answer your original question.

    I still want to post my solution in case others, like me, stumble across your question looking for a workaround.

    If you set your ConverterCulture in a CustomBinding class and use this CustomBinding instead of Binding in you xaml, it works at design time too.

    public class CultureAwareBinding : System.Windows.Data.Binding
    {
        public CultureAwareBinding()
        {
            ConverterCulture = CultureInfo.CurrentCulture;
        }
    }
    

    You can use it in your xaml like this.

    <TextBlock Text="{CultureAwareBinding Source={x:Static s:DateTime.Now}, StringFormat=Date: {0:dddd, MMMM dd}}"/>
    

    As an additional benefit this allows you to change the ConverterCulture later in one single place if needed. Also you can set other properties like StringFormat like this.