1

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

1 回答 1

2

你所拥有的是不正确的。ListBox 将自动将项目包装在 ListBoxItem 的实例中。在您的情况下,您将在为您自动创建的项目中显示一个 ListBoxItem(来自您的 DataTemplate)。

您应该使用ItemContainerStyle在自动创建的 ListBoxItem 上设置属性。

于 2011-05-25T15:51:09.367 回答