6

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.

Is this possible?

Currently: (Displays "SQLSERVER1")

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

Desired: (Display "Connection: 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. What am I doing wrong?

Joe Bauer
  • 572
  • 1
  • 9
  • 22

4 Answers4

5

The following works for me as of .NET 5:

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

where ProductName is defined as:

public static string ProductName {get { ... ; } }
dotNET
  • 33,414
  • 24
  • 162
  • 251
3

MenuItem provides a HeaderStringFormat property that you should use:

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

Actually, that property is part of HeaderedItemsControl, which MenuItem happens to extend.

The StringFormat property is just ignored.

Grant Winney
  • 65,241
  • 13
  • 115
  • 165
2

I suffered a similar problem and got around it by utilising ContentControl and it's separate ContentStringFormat property:

<TextBlock Cursor="Help" Text="Hello World" >
    <TextBlock.ToolTip>
        <ContentControl Content="{Binding Path=SomeProperty, Source={x:Static local:SomeStaticClass}}" ContentStringFormat="Hello {0}" />
    </TextBlock.ToolTip>
</TextBlock>
maxp
  • 24,209
  • 39
  • 123
  • 201
-1

StringFormat is disregarded for Content and Header, because their TargetType is not System.String. Those properties have corresponding *StringFormat properties to get around that limitation.