简体   繁体   English

绑定到静态类属性和 StringFormat

[英]Binding to Static class property and StringFormat

I am able to bind a static class property to a MenuItem header, but I cannot determine how to include a StringFormat so that I can display hard-coded text in addition to the property.我能够将静态类属性绑定到 MenuItem 标头,但我无法确定如何包含 StringFormat 以便我可以显示除该属性之外的硬编码文本。

Is this possible?这可能吗?

Currently: (Displays "SQLSERVER1")当前:(显示“SQLSERVER1”)

Header="{x:Static settings:Settings.CurrentServer}"

Desired: (Display "Connection: SQLSERVER1")所需:(显示“连接:SQLSERVER1”)

Header="{Binding Source={x:Static Settings:Settings.CurrentServer},StringFormat='Connection: {0}'}"

When I try the 'Desired' line in the XAML the StringFormat is ignored entirely.当我尝试 XAML 中的“Desired”行时,StringFormat 被完全忽略。 What am I doing wrong?我究竟做错了什么?

MenuItem provides a HeaderStringFormat property that you should use: MenuItem提供了一个您应该使用的HeaderStringFormat属性:

<MenuItem Header="{Binding Source={x:Static Settings:Settings.CurrentServer}}"
          HeaderStringFormat="Connection: {0}" />

Actually, that property is part of HeaderedItemsControl , which MenuItem happens to extend.实际上,该属性是HeaderedItemsControl一部分,而MenuItem恰好扩展了该属性。

The StringFormat property is just ignored. StringFormat属性只是被忽略。

I suffered a similar problem and got around it by utilising ContentControl and it's separate ContentStringFormat property:我遇到了类似的问题,并通过使用ContentControl解决了它,它是单独的ContentStringFormat属性:

<TextBlock Cursor="Help" Text="Hello World" >
    <TextBlock.ToolTip>
        <ContentControl Content="{Binding Path=SomeProperty, Source={x:Static local:SomeStaticClass}}" ContentStringFormat="Hello {0}" />
    </TextBlock.ToolTip>
</TextBlock>

The following works for me as of .NET 5:从 .NET 5 开始,以下对我有用:

<Window Title="{Binding Source={x:Static vm:ApplicationSettings.ProductName}, StringFormat='{}{0} Document'}" />

where ProductName is defined as:其中ProductName定义为:

public static string ProductName {get { ... ; } }

StringFormat is disregarded for Content and Header, because their TargetType is not System.String.对于 Content 和 Header,StringFormat 被忽略,因为它们的 TargetType 不是 System.String。 Those properties have corresponding *StringFormat properties to get around that limitation.这些属性具有相应的 *StringFormat 属性来绕过该限制。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM