Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get the ListBoxItem in a ListBox

I am trying to change the Control template on a ListBoxItem when It is selected from the ListBox. To do so, I was going to get the selected ListBoxItem from the ListBox itself, and set the control template on that. How would i go about doing this? I have tried, SelectedItem and that returns the bound object within the ListBoxItem.

like image 297
Ben Avatar asked Aug 24 '10 12:08

Ben


People also ask

How do I know if an item is selected in ListBox?

To determine the items that are selected, you can use the Selected property of the list box. The Selected property of a list box is an array of values where each value is either True (if the item is selected) or False (if the item is not selected).

How to use ListBox in WPF c#?

On button click event handler, we add the content of TextBox to the ListBox by calling ListBox. Items. Add method. Now, if you enter text in the TextBox and click Add Item button, it will add contents of the TextBox to the ListBox.

How to bind ListBox in WPF c#?

You can use data binding to bind data to the individual items. The following example shows how to create a ListBox that populates the ListBoxItem elements by data binding to a data source called Colors. In this case it is not necessary to use ListBoxItem tags to specify the content of each item.

How do I select a ListBox?

To select an item in a ListBox, we can use the SetSelect method that takes an item index and a true or false value where the true value represents the item to be selected. The following code snippet sets a ListBox to allow multiple selection and selects the second and third items in the list: listBox1.


2 Answers

You can retrieve the item container from the bound item by using the ItemContainerGenerator :

object selectedItem = listBox.SelectedItem;
ListBoxItem selectedListBoxItem = listBox.ItemContainerGenerator.ContainerFromItem(selectedItem) as ListBoxItem;
like image 86
Thomas Levesque Avatar answered Sep 23 '22 12:09

Thomas Levesque


Now you can do it with this:

ListBoxItem container = listBox.ContainerFromIndex(listBox.SelectedIndex) as ListBoxItem;

The ItemContainerGenerator.ContainerFromItem() function seems like obsolete now.

If you have set the Item Template for the ListBox then you can get it from

UIElement item= container.ContentTemplateRoot;
like image 30
Anup Sharma Avatar answered Sep 24 '22 12:09

Anup Sharma