问题描述
|
我只显示一个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上设置属性。