我如何,或者我可以在TextBlock上为StringFormat使用静态资源?

Mat*_*ker 8 c# wpf xaml string-formatting

我有一个显示日期/时间的文本块.对于应用程序中的某些控件,时钟的外观可能会有所不同,就颜色和字体而言,但我希望日期和时间具有相同的格式.

我知道我可以像这样设置StringFormat属性:

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

但是,我不知道如何将字符串格式拉出到单独的字符串资源字典中.我尝试做类似以下的事情,但日期时间字符串根本没有出现.

<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" />
Run Code Online (Sandbox Code Playgroud)

这可以完成吗?如果是这样,怎么样?

谢谢

Jes*_*ood 15

看来你只需删除{}:

<system:String x:Key="MyFormat">{0:h\:mm tt}</system:String>
Run Code Online (Sandbox Code Playgroud)

所述{}需要的属性值,以防止它们被解释为一个标记扩展.但是,使用属性元素语法,您不再需要{}因为花括号在该上下文中没有特殊含义.