Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

What I Learned In WP7 – Issue 16

DZone's Guide to

What I Learned In WP7 – Issue 16

· Mobile Zone
Free Resource
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;
}

 

Topics:

Published at DZone with permission of Jeff Blankenburg, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

THE DZONE NEWSLETTER

Dev Resources & Solutions Straight to Your Inbox

Thanks for subscribing!

Awesome! Check your inbox to verify your email so you can start receiving the latest in tech news and resources.

X

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}