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.
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).
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.
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.
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.
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;
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;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With