For example,
if you place StackPanel objects in your list, the ListBox.SelectedItem object will be a
StackPanel. If you place StackPanel objects wrapped by ListBoxItem objects, the
ListBox.SelectedItem object will be a ListBoxItem, so code accordingly.
The ListBoxItem offers a little bit of extra functionality from what you get with directly
nested objects. Namely, it defines an IsSelected property that you can read (or set) and a
Selected and Unselected event that tells you when that item is highlighted. However, you
can get similar functionality using the members of the ListBox class, such as the SelectedItem
(or SelectedItems) property, and the SelectionChanged event.
Interestingly, there??™s a technique to retrieve a ListBoxItem wrapper for a specific object
when you use the nested object approach. The trick is the often overlooked Container-
FromElement() method. Here??™s the code that checks whether the first item is selected in a
list using this technique:
Dim selectedObject As DependencyObject
selectedObject = CType(lst.SelectedItems(0), DependencyObject))
Dim selectedItem As ListBoxItem
selectedItem = CType(lst.ContainerFromElement(selectedItem, ListBoxItem)
MessageBox.Show(("IsSelected: " + selectedItem.IsSelected.ToString))
The ComboBox
The ComboBox is similar to the ListBox control.
Pages:
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413