I have a listbox which is populated through databinding to an 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>
I want to get the string value of just username for whatever item is selected. Generally in the past I’ve done this with a convoluted indexing system, but there must be a way to do it from listbox_users.Items or listbox_users.SelectedItem. I have no idea how to accomplish this in the context of databinding, I’m still very new to the concept
Since you are using data binding and setting the
ItemTemplate, theListBox.SelectedItemwill return theDataContextof that item and not the templated element. I assume that the ItemsSource is a List of some type of view model. Here is an example where the ItemsSource is of typeObservableCollection<UserViewModel>