Set combobox Item in code Behind UWP

≯℡__Kan透↙ 提交于 2019-12-11 16:39:33

问题


I have seen how to select the item from the index by code behind, but how can i select it from code behind knowing the string of the item?

combobox code xaml:

<ComboBox x:Name="ComboBoxOne" VerticalAlignment="Center" HorizontalAlignment="Center" Height="40" Width="200">
      <ComboBoxItem Content="blue"/>
      <ComboBoxItem Content="red"/>
      <ComboBoxItem Content="green"/>
</ComboBox>

combobox code behind:

ComboBoxOne.SelectedIndex = 1;

But how to select the item knowing for example green? Is possible?

I tried with ComboBoxOne.PlaceholderText

ComboBoxOne.PlaceholderText="green"

But then I can not use the selecteditem.

Thanks in advance!


回答1:


First you need to get the Items of the ComboBox as a List to find the Index of the item that you want to select by string. Since this will be a List<String> you can do something like below.

List<String> lstItems = ComboBoxOne.Items
                            .Cast<ComboBoxItem>()
                            .Select(item => item.Content.ToString())
                            .ToList();

and then you can get the index using Linq and assign it to Selected Index. Like below.

ComboBoxOne.SelectedIndex = lstItems.FindIndex(a => a.Equals("green"));

Good Luck.



来源:https://stackoverflow.com/questions/46978988/set-combobox-item-in-code-behind-uwp

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!