简体   繁体   English

Combobox SelectedItem 在 UWP 中不起作用

[英]Combobox SelectedItem is not working in UWP

I have a Combobox with some items, i fill combobox this way:我有一个 Combobox 和一些项目,我这样填写 combobox:

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:和 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.问题是没有选择默认项目(SelectedItem),我需要combobox中的select默认项目。

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

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? Settings.DefaultTranslation是否有可能不等于项目集合中的任何items ,这就是没有发生分配的原因? Maybe you can add it to your collection Settings.DefaultTranslation like the first element and set cmbTranslators.SelectedIndex = 0也许你可以像第一个元素一样将它添加到你的集合Settings.DefaultTranslation中并设置cmbTranslators.SelectedIndex = 0

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM