Home > OS >  Combobox SelectedItem is not working in UWP
Combobox SelectedItem is not working in UWP

Time:05-23

I have a Combobox with some items, i fill combobox this way:

var files = Directory.GetFiles(Constants.TranslationsPath);
var items = new ObservableCollection<Translation>();
using var db = new AlAnvarDBContext();
if (files.Count() > 0)
 {
   foreach (var file in files)
   {
     var id = Path.GetFileNameWithoutExtension(file);
     var trans = db.Translations.Where(x => x.Link.Contains(id)).FirstOrDefault();
     if (trans != null)
     {
      items.Add(trans);
     }
   }
   cmbTranslators.ItemsSource = items;
   cmbTranslators.SelectedItem = Settings.DefaultTranslation;
 }

and xaml:

<ComboBox x:Name="cmbTranslators">
                <ComboBox.ItemTemplate>
                    <DataTemplate x:DataType="table:Translation">
                        <StackPanel Orientation="Horizontal">
                            <TextBlock Text="{x:Bind Name}"/>
                            <TextBlock Text="-"/>
                            <TextBlock Text="{x:Bind Language}"/>
                            <TextBlock Text="-"/>
                            <TextBlock Text="{x:Bind Translator}"/>
                        </StackPanel>
                    </DataTemplate>
                </ComboBox.ItemTemplate>
            </ComboBox>

The problem is that the default item (SelectedItem) is not selected and i need to select default item in combobox.

CodePudding user response:

cmbTranslators.SelectedItem = cmbTranslators.Items.Where(x=>((Translation)x).Id == Settings.DefaultTranslation.Id).FirstOrDefault();

CodePudding user response:

Is it possible that the Settings.DefaultTranslation is not equal to any of the items in the item collection and that is why the assignment did not occur? Maybe you can add it to your collection Settings.DefaultTranslation like the first element and set cmbTranslators.SelectedIndex = 0

  • Related