Reputation: 77
I have a ListBox
(or a ComboBox
, I've tried both) where the items are added directly through ListBoxItem
(ComboBoxItem
) elements.
The data are CultureInfo
objects coming from two ObjectDataProvider
resources in the element (or in some place above). The CultureInfo.GetCultureInfo
static method is called.
In a word, I would like to have a ListBox/ComboBox
populated with some CultureInfo
entries.
The data binding works fine, but on setting DisplayMemberPath
to one of the CultureInfo
properties (such as DisplayName
- I would like "English" to be displayed, not "en-US") nothing happens.
Oddly, if I try with ComboBox
and select one of the items, DisplayMemberPath
works on the selected value (which is shown in the text box), but not on the dropdown list.
My question is: am I missing something? Or does DisplayMemberPath
not work with direct items and only when ItemsSource
is bound to a collection (just a guess)?
<ListBox x:Name="LangListBox" DisplayMemberPath="DisplayName">
<ListBox.Resources>
<ObjectDataProvider x:Key="EngCultureInfoProvider" ObjectType="{x:Type Globalization:CultureInfo}" MethodName="GetCultureInfo">
<ObjectDataProvider.MethodParameters>
<System:String>en-US</System:String>
</ObjectDataProvider.MethodParameters>
</ObjectDataProvider>
<ObjectDataProvider x:Key="ItaCultureInfoProvider" ObjectType="{x:Type Globalization:CultureInfo}" MethodName="GetCultureInfo">
<ObjectDataProvider.MethodParameters>
<System:String>it-IT</System:String>
</ObjectDataProvider.MethodParameters>
</ObjectDataProvider>
</ListBox.Resources>
<ListBoxItem Content="{Binding Source={StaticResource EngCultureInfoProvider}}"/>
<ListBoxItem Content="{Binding Source={StaticResource ItaCultureInfoProvider}}"/>
</ListBox>
Note: using ItemTemplate does not work either.
...
<ListBox.ItemTemplate>
<DataTemplate>
<TextBlock Text="{Binding DisplayName}"/>
</DataTemplate>
</ListBox.ItemTemplate>
...
Upvotes: 2
Views: 170
Reputation: 35681
Currently each ListBoxItem displays result of ToString()
method on CultureInfo
object.
DisplayMemberPath
and ItemTemplate
don't work for items, because ListBoxItem
are added directly, not created by ListBox
.
Add DisplayName
in binding path:
<ListBoxItem Content="{Binding Source={StaticResource EngCultureInfoProvider}, Path=DisplayName}"/>
<ListBoxItem Content="{Binding Source={StaticResource ItaCultureInfoProvider}, Path=DisplayName}"/>
or
create default Style for ListBoxItem with custom ContentTemplate:
<ListBox x:Name="LangListBox" DisplayMemberPath="DisplayName">
<ListBox.Resources>
<Style TargetType="ListBoxItem">
<Setter Property="ContentTemplate">
<Setter.Value>
<DataTemplate DataType="{x:Type Globalization:CultureInfo}">
<TextBlock Text="{Binding DisplayName}"/>
</DataTemplate>
</Setter.Value>
</Setter>
</Style>
</ListBox.Resources>
<ListBoxItem Content="{Binding Source={StaticResource EngCultureInfoProvider}}"/>
<ListBoxItem Content="{Binding Source={StaticResource ItaCultureInfoProvider}}"/>
</ListBox>
Upvotes: 2