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

时间:2022-06-05 02:34:37

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:

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

<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 个解决方案

#1


12  

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.

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

#1


12  

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.

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