Why are there 2 ListBoxItems in the Visual Tree?
I am only displaying the selected element of a ListBox (yeah I know) ... And I am trying to understand why if I have a single ListBox.ItemTemplate with a single child of ListBoxItem, I have to traverse 2 ListBoxItems to access the element named "thisListBoxItem"? It seems like there should only be one visual ListBoxItem element.
my XAML
<ListBox Name="cjisDisplayItemListBox" SelectionChanged="cjisDisplayItemListBox_SelectionChanged_1">
<ListBox.ItemTemplate >
<DataTemplate>
<ListBoxItem Name="thisListBoxItem" Visibility="Collapsed">
<!-- some TextBlocks with bindings here -->
</ListBoxItem>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
//First I cast SelectedItem to a ListBoxItem (myListBoxItem) // then I have to descend to a lower ListBoxItem via the FindName property..
private void cjisDisplayItemListBox_SelectionChanged_1(object sender, SelectionChangedEventArgs e)
{
ListBox lb = sender as ListBox;
object item = lb.SelectedItem as object;
ListBoxItem myListBoxItem = (ListBoxItem)(lb.ItemContainerGenerator.ContainerFromItem(item));开发者_开发问答
ContentPresenter myContentPresenter = FindVisualChild<ContentPresenter>(myListBoxItem);
if (myContentPresenter == null) return;
DataTemplate myDataTemplate = myContentPresenter.ContentTemplate;
ListBoxItem temp = (ListBoxItem)myDataTemplate.FindName("thisListBoxItem", myContentPresenter);
if (myListBoxItem.IsSelected) temp.Visibility = System.Windows.Visibility.Visible;
}
What you have is incorrect. The ListBox will automatically wrap the items in instances of ListBoxItem. In your case, you are displaying a ListBoxItem (from your DataTemplate) in the one that is automatically created for you.
You should use ItemContainerStyle to set properties on the automatically created ListBoxItem.
精彩评论