如何从ListBox(ListBoxItems)Windows Universal将数据获取为string/int
本文关键字:数据获取 string int Universal Windows ListBox ListBoxItems | 更新日期: 2023-09-27 18:28:55
我希望以前没有人问过这样的问题,我做了一些研究,但没有一个答案对我有效,所以我决定自己问。我正在制作一个简单的应用程序,用户必须从列表中选择几个选项,我已经制作了ListBox和项目列表。
<ListBox x:Name="Continent">
<ListBoxItem Content="Europe" Foreground="White" />
<ListBoxItem Content="Africa" Foreground="White"/>
<ListBoxItem Content="Asia" Foreground="White"/>
</ ListBox>
我是Windows通用平台的新手,所以我希望我做得对。
无论如何,现在我想,在用户按下"转发"按钮后,将数据收集到一个字符串中。我尝试过:
string selected = Continent.SelectedItem.Content;
和
string selected = Continent.SelectedItems[0].Content;
我也尝试添加"文本"值,但它不允许。
有人知道怎么做吗?最简单的方法是什么?
提前感谢
我认为这里的一个合理答案是帮助您学习如何自己调试问题,并在学习平台的过程中发现问题。
你的例子很简单。大多数情况下,Content会被设置为类的实例,就像Continent对象一样。然而,您所拥有的一切都很好,您只需要使用调试器来了解您要返回的对象。
对此:var data = Continent.SelectedItem;
,您可以在即时窗口中看到以下内容:
data is ListBoxItem
true
(data as ListBoxItem).Content
"Africa"
(data as ListBoxItem).Content is string
true
((ListBoxItem)data).Content
"Africa"
当您陷入困境时,可以在调试器中玩一玩,使用Immediate window
或查看Locals
来发现返回的类型。
所以你的答案可能是:
string selected = ((ListBoxItem)data).Content
祝你的项目好运。
使用listboxitem的内容不是一个好主意。这些控件具有包含逻辑数据的特定属性,它被称为"标记"。您可以像复杂的对象一样将所需的一切都放在其中,并具有不同的显示(内容)值。
所以你必须将你的xaml更改为:
<ListBox x:Name="Continent">
<ListBoxItem Content="Europe" Foreground="White" Tag="europe" />
<ListBoxItem Content="Africa" Foreground="White" Tag="africa"/>
<ListBoxItem Content="Asia" Foreground="White" Tag="asia"/>
</ListBox>
以及你的代码:
foreach (ListBoxItem selectedItem in Continent.SelectedItems)
{
var continentTag = selectedItem?.Tag as string;
if (continentTag != null)
{
//Do your stuff here
}
}