我有一个列表框,通过数据绑定填充到ObservableCollection
<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.Items或listbox_users.SelectedItem中完成。我不知道如何在数据绑定的上下文中实现这一点,我仍然是这个概念的新手
答案 0 :(得分:2)
由于您正在使用数据绑定并设置ItemTemplate
,因此ListBox.SelectedItem
将返回该项目的DataContext
而不是模板化元素。我假设ItemsSource是某种类型的视图模型的List。以下是ItemsSource类型为ObservableCollection<UserViewModel>
UserViewModel selectedUser = listBox_user.SelectedItem as UserViewModel;
string username = selectedUser.username;