如何获取列表框中两列项中第一列的字符串值

本文关键字:一列 字符串 何获取 获取 列表 两列 | 更新日期: 2023-09-27 18:35:12

我有一个列表框,它通过数据绑定到可观察集合来填充

<ListBox Height="198" HorizontalAlignment="Left" Margin="12,45,0,0" Name="listBox_users" VerticalAlignment="Top" Width="204" ItemsSource="{Binding}">
            <ListBox.ItemTemplate>
            <DataTemplate>
                <StackPanel Orientation="Horizontal">
                    <TextBlock Text="{Binding username}" Name="left" Width="50" />
                    <TextBlock Text="{Binding real_name}" Name="right" Width="100" />
                </StackPanel>
            </DataTemplate>
            </ListBox.ItemTemplate>
        </ListBox>

我想为选择的任何项目获取用户名的字符串值。通常,在过去,我使用复杂的索引系统来做到这一点,但必须有一种方法可以从listbox_users做到这一点。项目或listbox_users。选定项。我不知道如何在数据绑定的上下文中完成此操作,我对这个概念仍然很陌生

如何获取列表框中两列项中第一列的字符串值

由于您使用的是数据绑定并设置ItemTemplate,因此ListBox.SelectedItem将返回该项的DataContext,而不是模板化元素。我假设 ItemsSource 是某种类型的视图模型的列表。下面是一个示例,其中 ItemsSource 的类型为 ObservableCollection<UserViewModel>

UserViewModel selectedUser = listBox_user.SelectedItem as UserViewModel;
string username = selectedUser.username;