How do I, or can I use a static resource for the StringFormat on a TextBlock?

6.1k views Asked by At

I have a text block that is displaying the date/time. The look of the clock may be different on some controls in the application, as far as color and maybe font, but I want the date and time to have the same format.

I know I can set the StringFormat property like so:

<TextBlock Text="{Binding CurrentDateTime, StringFormat='{}{0:h\:mm tt}'}" Foreground="White" FontFamily="Proxima Nova Rg" FontSize="20" />

However, I don't know how to pull the string format out into a separate string resource dictionary. I tried to do something like the following, but the date time string didn't appear at all.

<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
                    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
                    xmlns:system="clr-namespace:System;assembly=mscorlib">
    <system:String x:Key="MyFormat">{}{0:h\:mm tt}</system:String>
</ResourceDictionary>

<!-- In another file -->
<TextBlock Text="{Binding CurrentDateTime, StringFormat={StaticResource MyFormat}}" Foreground="White" FontFamily="Proxima Nova Rg" FontSize="20" />

Can this be done at all? If so, how?

Thanks

1

There are 1 answers

2
Jesse Good On BEST ANSWER

It appears you just have to remove the {}:

<system:String x:Key="MyFormat">{0:h\:mm tt}</system:String>

The {} is required for attribute values to prevent them from being interpreted as a markup extension. However, with property element syntax, you no longer need the {} because curly braces do not have special meaning in that context.