Silverlight: Getting the parent ListBox SelectedItem property of a child Button

Thanks to Anthony on StackOverflow for solving this problem for me.

I had the following XAML code, having removed the styling and formatting tags:

<ListBox Name=”ManageImageList”>
    <ListBox.ItemTemplate>
        <DataTemplate>
            <StackPanel>
                <Image Name=”ManageImageThumbnail” Source=”{Binding ImageName}” />
                <StackPanel Orientation=”Vertical” >
                    <TextBlock Name=”ManageImageUrl” Text=”{Binding ImageName}” />
                    <TextBlock Name=”ManageImageComment” Text=”{Binding Comment}” />
                </StackPanel>
                <Button Name=”ManageImageDelete” Click=”ManageImageDelete_Click” Content=”X” />
           </StackPanel>
        </DataTemplate>
   </ListBox.ItemTemplate>
</ListBox>

The ListBox was bound to an ObservableCollection. I wanted to give focus to the parent ListBox item when the button is clicked, making it the SelectedItem of the ListBox. But I didn’t know how to do that.

Anthony provided this answer:

private void ManageImageDelete_Click(object sender, RoutedEventArgs e)
{
     ManageImageList.SelectedItem = ((Button)sender).DataContext;
}

Exactly what I needed, and it worked perfectly.

Advertisements
  1. #1 by Hugo on March 1, 2012 - 3:39 pm

    Thank you… this is the answer that I was looking for!

  2. #2 by OscarDaBoscar on December 19, 2012 - 5:04 pm

    Brilliant, thank you.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: