我只显示 ListBox 的选定元素(是的,我知道)......而且我试图理解为什么如果我有一个 ListBox.ItemTemplate 和一个 ListBoxItem 的单个子项,我必须遍历 2 个 ListBoxItems 才能访问该元素命名为“thisListBoxItem”?似乎应该只有一个视觉 ListBoxItem 元素。
我的 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;
}