Silverlight / WPF - selected item for listbox - Asked By Ramachandran on 09-Jun-12 04:36 AM

I am having a list box with four user control Xaml as a items in the list. i want to take the specific usercontrol Xaml as the selected item in the listbox. plse tell me how to take the selected user control item as a Selected item. plse tell me
[)ia6l0 iii replied to Ramachandran on 11-Jun-12 09:42 AM
I hope your markup is like below:

ListBoxItems being instances of user control. Attach the selection changed event handler like below.
<ListBox x:Name="items" SelectionMode="Single" SelectionChanged="listboxselectionchanged" >
<ListBoxItem><UserControl></UserControl></ListBoxItem>
<ListBoxItem><UserControl></UserControl></ListBoxItem>
<ListBoxItem><UserControl></UserControl></ListBoxItem>
<ListBoxItem><UserControl></UserControl></ListBoxItem>
</ListBox>


And in the selectionchanged event handler, access the listbox like below.
private void listboxselectionchanged(object sender, SelectionChangedEventArgs args)
{
  ListBoxItem item = ((sender as ListBox).SelectedItem as ListBoxItem);
 
//The item should be  casted to your user control type.
}

Or you could have them in ItemTemplate,
<ListBox x:Name="items">
    <ListBox.ItemTemplate>
        <DataTemplate>
            <ns:usercontrolname DataContext="{Binding}"/>
        </DataTemplate>
    </ListBox.ItemTemplate>
</ListBox>


Then access the selecteditem from the containerfromItem method.
ListBoxItem selectedItem = (ListBoxItem)(lbname.ItemContainerGenerator.ContainerFromItem(lbname.Items.CurrentItem));

Hope this helps.