Eric Ouellet Eric Ouellet - 3 months ago 13
C# Question

Why does StringFormat have no effect on the binding of my MenuItem.Header?

All of my 6 samples have "StringFormat" in their binding but none is applied and I'm only getting the value without any formatting.

Any idea what I do wrong?

<MenuItem Header="{Binding SeriesNearMouse.Count, StringFormat='Series {0}'}">
</MenuItem>

<MenuItem DataContext="SeriesNearMouse">
<MenuItem.Header>
<Binding Path="Count"
StringFormat="Series{0:D}test">
</Binding>
</MenuItem.Header>

</MenuItem>
<MenuItem>
<MenuItem.Header>
<Binding Path="SeriesNearMouse.Count"
StringFormat="Series{0}">
</Binding>
</MenuItem.Header>
</MenuItem>

<MenuItem Header="{Binding SeriesNearMouse.Count, StringFormat='{}Series {0}'}">
</MenuItem>

<MenuItem DataContext="SeriesNearMouse">
<MenuItem.Header>
<Binding Path="Count"
StringFormat="{}Series{0:D}test">
</Binding>
</MenuItem.Header>

</MenuItem>
<MenuItem>
<MenuItem.Header>
<Binding Path="SeriesNearMouse.Count"
StringFormat="{}Series{0}">
</Binding>
</MenuItem.Header>
</MenuItem>

Answer

It is probably not working how you expect because MenuItem.Header is an object, not a string.

Something like this should work, since Run.Text is a string:

<MenuItem>
  <MenuItem.Header>
    <Run Text="{Binding SeriesNearMouse.Count, StringFormat='Series {0}', Mode=OneWay}" />
  </MenuItem.Header>
</MenuItem>