Yesterday, I had a developer reach out to me about a seemingly simple problem, but it wasn’t until I looked at it in a greenfield project that I could solve it quickly. In the XAML below, I have a ListBox that I bind a List of objects to. What the developer was trying to do was get the text in the “AlternateText” TextBox for the item clicked.
<Grid x:Name="ContentPanel" Grid.Row="1" Margin="12,0,12,0"> <ListBox x:Name="masterList" SelectionChanged="masterList_SelectionChanged"> <ListBox.ItemTemplate> <DataTemplate> <StackPanel Orientation="Horizontal"> <Image x:Name="ActionImage" Source="{Binding ActionImage}" Width="100" Height="100"/> <StackPanel> <TextBlock x:Name="ActionText" Text="{Binding ActionText}" FontSize="40" Width="300" /> <TextBlock x:Name="AlternateText" Text="{Binding ActionDescription}" /> </StackPanel> </StackPanel> </DataTemplate> </ListBox.ItemTemplate> </ListBox> </Grid>
The important thing to remember here is that when you call the SelectionChanged event on a ListBox, the ListBox still recognizes each item as its original object. Therefore, you should actually be trying to access the specific object that was selected, and then access the properties of that object, instead of the XAML elements that make up the ListBox’s layout.
Here’s the solution we implemented, where TestClass is the object type we’re using:
private void masterList_SelectionChanged(object sender, SelectionChangedEventArgs e) { ListBox testList = sender as ListBox; TestClass testText = (TestClass)testList.SelectedItem; string whatImLookingFor = testText.AlternateText; }
Leave a Reply