views:

124

answers:

1

I just noticed a strange behavior which looks like a bug. Consider the following XAML :

<Page
  xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
  xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
  xmlns:sys="clr-namespace:System;assembly=mscorlib">
  <Page.Resources>
    <x:Array x:Key="data" Type="{x:Type sys:String}">
        <sys:String>Foo</sys:String>
        <sys:String>Bar</sys:String>
        <sys:String>Baz</sys:String>
    </x:Array>
  </Page.Resources>
  <StackPanel Orientation="Vertical">
      <Button>Boo</Button>
      <ComboBox Name="combo" ItemsSource="{Binding Source={StaticResource data}}" ItemStringFormat="##{0}##" />
      <TextBlock Text="{Binding Text, ElementName=combo}"/>
  </StackPanel>
</Page>

The ComboBox displays the values as "##Foo##", "##Bar##" and "##Baz##". But the TextBlock displays the selected values as "Foo", "Bar" and "Baz". So the ItemStringFormat is apparently ignored for the Text property...

Is that a bug ? If it is, is there a workaround ?
Or am I just doing something wrong ?

+1  A: 

It's not a bug: ItemStringFormat is just a shortcut for "data template having a textblock bound to the value with the specified string format set in the binding". Text however is generally used when IsEditable is true and represents user-input. When you have anything other than strings in your list, it's preferable to use the SelectedItem than the Text. In any case, the following code will reapply the format to the text:

<TextBlock Text="{Binding ElementName=combo, Path=Text, StringFormat='##{0}##'}"/>
Julien Lebosquain
Thanks for your answer. But my problem is a bit more complex... I need to retrieve the Text of the ComboBox in my ViewModel, so I use a binding with Mode=OneWayToSource. The ItemStringFormat I use is defined in the resources of the assembly containing the template, but the ViewModel is in another assembly, and can't access this resource... So I will have to duplicate this resource in the ViewModel assembly. I don't like that, but at least it will work...
Thomas Levesque