ComboBox with localizable ComboBoxItems specified in XAML

1.5k views Asked by At

I have a ComboBox which I'd like to populate with members of an enum, with localized representative strings. I know the standard way to do this is to make a Dictionary in codebehind with the enum values as keys and the text as values, and then set the ItemsSource to that. But then I wouldn't be able to use my sexy MarkupExtension. So, I'd like to do this in XAML. I thought it would be easy; here's what I have:

        <ComboBox x:Name="cmbNewTabPos"
            DisplayMemberPath="Content"
            SelectedValue="{Binding Path=NewTabPosition}"
            SelectedValuePath="Tag">
            <ComboBoxItem
                Content="{qt:Resx Key=SomeKey, Index=0}" 
                Tag="{x:Static qt:TabPos.Left}"/>
            <ComboBoxItem
                Content="{qt:Resx Key=SomeKey, Index=1}"
                Tag="{x:Static qt:TabPos.Right}"/>
            <ComboBoxItem
                Content="{qt:Resx Key=SomeKey, Index=2}"
                Tag="{x:Static qt:TabPos.Leftmost}"/>
            <ComboBoxItem
                Content="{qt:Resx Key=SomeKey, Index=3}" 
                Tag="{x:Static qt:TabPos.Rightmost}"/>
        </ComboBox>

It almost works; the dropdown is populated correctly, the binding is working, I can see the selected value when I pull down the dropdown, but the box part of the combobox remains blank no matter what I do. What am I doing wrong here?

1

There are 1 answers

1
Shomron On BEST ANSWER

I write this little example and it works fine.

<Window x:Class="MainWindowCommandBinding.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Title="MainWindow" Height="350" Width="525">
<Grid>
    <Grid.Resources >
        <Point x:Key="1_2" X="1" Y="2"/>
        <Point x:Key="1_3" X="1" Y="3"/>
        <Point x:Key="1_4" X="1" Y="4"/>
        <Point x:Key="1_5" X="1" Y="5"/>
    </Grid.Resources>
    <ComboBox x:Name="cmbNewTabPos"
        DisplayMemberPath="Y"
        SelectedValuePath="Tag"
        SelectedValue="1"
         Margin="0,12,0,0" HorizontalAlignment="Left" Width="135" Height="37" VerticalAlignment="Top">
        <ComboBoxItem Content="{StaticResource ResourceKey=1_2}" Tag="1"/>
        <ComboBoxItem Content="{StaticResource ResourceKey=1_3}" Tag="2"/>
        <ComboBoxItem Content="{StaticResource ResourceKey=1_4}" Tag="3"/>
        <ComboBoxItem Content="{StaticResource ResourceKey=1_5}" Tag="4"/>
    </ComboBox>
</Grid>

I think you are not using DisplayeMemberPath="Content" properly. That is used to specify which value to display from the selected object. The selected object is not the selected ComboBoxItem but what is in the Content Property of the selected ComboBoxItem. But from your code I can see that object in your ComboBoxItems only have two properties named "Key" and "Index". Hope this help. If I misunderstood, please let me know.