2011-05-25 27 views
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; 
        } 

回答

2

你有什麼是不正確的。 ListBox將自動將項目包裝在ListBoxItem的實例中。在你的情況下,你正在爲你自動創建一個ListBoxItem(來自你的DataTemplate)。

您應該使用ItemContainerStyle在自動創建的ListBoxItem上設置屬性。

相關問題