1

I need to select custom item under WPF Combobox by code behind. For example: "Spanish"

 UILanguages languages = new UILanguages();                
                languages.Add(
                        new UILanguage
                        {
                            Culture = "en",
                            SpecCulture = "en-US",
                            EnglishName = "English"
                        });

                languages.Add(
                    new UILanguage
                    {
                        Culture = "es",
                        SpecCulture = "es-ES",
                        EnglishName = "Spanish"
                    });

                CollectionViewSource cvs = new CollectionViewSource
                {
                    Source = languages
                };

                cmbLanguages.SetBinding(ItemsControl.ItemsSourceProperty, new Binding { Source = cvs });

Markup

  <ComboBox Grid.Column="1" Height="23" HorizontalAlignment="Left" Margin="0,1,0,0" 
              Name="cmbLanguages" VerticalAlignment="Top" Width="207"
           ItemsSource="{Binding Source={StaticResource UILanguagesViewSource}}" 
              />

Please, note that

but this Set SelectedItem of WPF ComboBox and this WPF combobox binding from code behind doesn't help at all.

Any clue?

Thank you!

Community
  • 1
  • 1
NoWar
  • 36,338
  • 80
  • 323
  • 498

2 Answers2

1

You'd need to set the SelectedValue property to the specific instance of your language. This could be done via something like:

// Get first element with proper name from the bound source
cmdLanguages.SelectedValue = languages.FirstOrDefault(l => l.EnglishName == "Spanish");
Reed Copsey
  • 554,122
  • 78
  • 1,158
  • 1,373
1

Or in addition to Reed's asnwer you can (pseudocode), first bind to a property

<ComboBox ... SelectedItem="{Binding Path=Selected}" />

In your UILanguage have a boolean property Selected

and from code behind do, something like this

UILanguage lang = languages.FirstOrDefault(l => l.EnglishName == "MyLanguage");
lang.Selected = true;

//update binding

Definitely more code, but pure WPF coding, in this case.

Tigran
  • 61,654
  • 8
  • 86
  • 123