1
我只顯示列表框的選定元素(yeah I know)...我想了解爲什麼如果我有一個ListBoxItemTemplate單個ListBoxItem的子項,我必須遍歷2個ListBoxItems來訪問元素命名爲「thisListBoxItem」?似乎應該只有一個可視的ListBoxItem元素。爲什麼Visual Tree中有2個ListBoxItems?
我的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>
//首先我投的SelectedItem到ListBoxItem的(myListBoxItem) //那我也下降到通過FindName屬性較低ListBoxItem的..
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;
}