在 UWP 背后的代码中设置组合框项 [英] Set combobox Item in code Behind UWP

查看:26
本文介绍了在 UWP 背后的代码中设置组合框项的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经看到了如何通过后面的代码从索引中选择项目,但是如何在知道项目字符串的情况下从后面的代码中选择它?

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?

组合框代码 xaml:

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>

后面的组合框代码:

ComboBoxOne.SelectedIndex = 1;

但是如何选择知道例如绿色的项目?可能吗?

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

我尝试使用 ComboBoxOne.PlaceholderText

I tried with ComboBoxOne.PlaceholderText

ComboBoxOne.PlaceholderText="green"

但是我不能使用selecteditem.

But then I can not use the selecteditem.

提前致谢!

推荐答案

首先需要获取ComboBoxItems作为List> 查找要按字符串选择的项目的索引.由于这将是一个 List,您可以执行如下操作.

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();

然后您可以使用 Linq 获取索引并将其分配给 Selected Index.如下图.

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"));

祝你好运.

这篇关于在 UWP 背后的代码中设置组合框项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆