【问题标题】:Get Content from Multiple ListBoxItems and Cast to String从多个 ListBoxItem 中获取内容并转换为字符串
【发布时间】:2015-12-06 00:55:21
【问题描述】:

在 Google 和搜索 stackoverflow 上花了很长时间,但解决方案不是我想要的,或者我的实施不太正确。不要认为这有什么大不了的,所以希望有人可以提供解决方案(有点菜鸟,所以需要更多细节让我知道)。

我正在尝试从 W8.1 通用 XAML 应用程序的列表框中获取多个项目的值,以便可以将它们传递给 SQLite DB(我认为是使用逗号分隔的“加入”语句的字符串)。 ListItems 的数据源目前是手动设置的各种值。

与此同时,我正在为字符串的文本设置一个标签作为测试,并且没有从在列表框中使用 Checkboxes 获得任何乐趣,所以我已更改为 ListBoxItems,但是我没有得到内容通过,就如下(选择两个列表项时):

Windows.UI.Xaml.Controls.ListBoxItem, Windows.UI.Xaml.Controls.ListBoxItem

显然我在关注内容,应该是“开发者”和“测试者”。这是 ListBox 的 XAML 和我当前的代码:

<TextBlock x:Name="lblAreas" HorizontalAlignment="Left" Margin="548,200,0,0" TextWrapping="Wrap" Text="Areas of Interest" VerticalAlignment="Top" RenderTransformOrigin="1.143,1.692" FontSize="13.333" Height="32" Width="336"/>
    <ListBox x:Name="lbAreas" HorizontalAlignment="Left" Height="231" Margin="548,241,0,0" VerticalAlignment="Top" Width="194" SelectionMode="Multiple">
        <ListBoxItem Content="Developer"/>
        <ListBoxItem Content="Tester"/>
    </ListBox>

后面的代码:

var listSelectedItems = lbAreas.SelectedItems.ToList();
string strSelectAreas = string.Join(", ", listSelectedItems);
lblAreas.Text = strSelectAreas;

希望这一切都说得通,我已经尝试了 SO 和其他地方的各种方法,这些方法看起来应该可以工作,但不完全在那里!感谢您的帮助。

【问题讨论】:

    标签: c# xaml listbox microsoft-metro windows-8.1


    【解决方案1】:

    SelectedItems 返回一个对象列表,这些对象的字符串表示是默认的(即类的名称)。您实际上是每个选定项目的 Content 属性,因此类似于:

    string selectAreas = string.Join(", ", lbAreas.SelectedItems.Select(i => i.Content));
    
    lblAreas.Text = selectAreas;
    

    注意:您可能必须将每个项目转换为 ListBoxItem

    string selectAreas = string.Join(", ", lbAreas.SelectedItems.Cast<ListBoxItem>()
                                                                .Select(i => i.Content));
    

    【讨论】:

    • 非常好,感谢 Dave 的快速回复,辛苦了!正如您提到的其他人阅读的那样,必须转换为 ListBoxItem。
    • 您可以使用文本绑定到 listBox.Items 以及将返回连接字符串的转换器。
    猜你喜欢
    • 2019-12-19
    • 1970-01-01
    • 1970-01-01
    • 2014-06-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-07-29
    相关资源
    最近更新 更多