Kim Homann
Kim Homann

Reputation: 3229

How can I display the current day of the week in XAML using the current regional settings?

I have the following XAML:

<Window x:Class="String_Format.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:s="clr-namespace:System;assembly=mscorlib"
        mc:Ignorable="d"
        Title="MainWindow" Height="150" Width="250">
    <StackPanel Margin="10">
        <TextBlock Name="TextBlock" Text="{Binding Source={x:Static s:DateTime.Now}, StringFormat=Date: {0:dddd, MMMM dd}}"/>
    </StackPanel>
</Window>

In the XAML designer in Visual Studio 2015 as well as in the running application, this displays as: "Date: Thursday, January 28". As I am on a German Windows 7 with regional settings set to "German (Germany)", I had actually expected: "Date: Donnerstag, Januar 28".

So I went and added the namespace

xmlns:c="clr-namespace:System.Globalization;assembly=mscorlib"

and altered my TextBlock to:

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

This indeed results in my desired behavior at runtime, but in the XAML designer, it says "Invalid Markup", and there's no preview of my window displayed an more.

This has been asked before, but I wanted to do it inside XAML, without using code behind, if possible.

So what's wrong with my XAML? I'd like to understand.

Upvotes: 1

Views: 1166

Answers (2)

unkreativ
unkreativ

Reputation: 480

Checkout if setting the Language on the Window helps, I do this in the code behind of a window / usercontrol etc:

this.Language = XmlLanguage.GetLanguage(Thread.CurrentThread.CurrentCulture.Name);

Upvotes: 0

ChrisF
ChrisF

Reputation: 137128

This indeed results in my desired behavior at runtime, but in the XAML designer, it says "Invalid Markup", and there's no preview of my window displayed an more.

This is because the added code: ConverterCulture={x:Static c:CultureInfo.CurrentCulture} cannot be resolved at design time. This results in the invalid markup and lack of display. It is resolved at runtime, which is why your date displays in the correct language/culture.

You can only solve this by moving this into code where you can check whether it's runtime or design time.

Upvotes: 1

Related Questions