为什么在可视树中有2个ListBoxItems?

问题描述

| 我只显示一个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;
                    }
    

解决方法

您所拥有的不正确。 ListBox将自动将项目包装在ListBoxItem的实例中。在您的情况下,您将在为您自动创建的列表框中显示一个ListBoxItem(来自DataTemplate)。 您应该使用ItemContainerStyle在自动创建的ListBoxItem上设置属性。     

相关问答

依赖报错 idea导入项目后依赖报错,解决方案:https://blog....
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下...
错误1:gradle项目控制台输出为乱码 # 解决方案:https://bl...
错误还原:在查询的过程中,传入的workType为0时,该条件不起...
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct...