c# – 为什么我的listboxitems没有崩溃?
发布时间:2020-12-15 08:37:41 所属栏目:百科 来源:网络整理
导读:如果我单击列表中间的项目,我希望除了1个元素之外的所有元素都会折叠.实际输出是剩下许多项目.为什么?这是整个计划. using System;using System.Collections.Generic;using System.Windows;using System.Windows.Controls;namespace WpfApplication2{ publi
如果我单击列表中间的项目,我希望除了1个元素之外的所有元素都会折叠.实际输出是剩下许多项目.为什么?这是整个计划.
using System; using System.Collections.Generic; using System.Windows; using System.Windows.Controls; namespace WpfApplication2 { public partial class MainWindow : Window { public class obj { } public MainWindow() { InitializeComponent(); List<obj> objList = new List<obj>(); for (int i = 0; i < 30; i++) objList.Add(new obj()); lb.ItemsSource = objList; } private void lb_SelectionChanged(object sender,SelectionChangedEventArgs e) { ListBox lb = sender as ListBox; for (int i = 0; i < lb.Items.Count; i++) { ListBoxItem tmp = (ListBoxItem)(lb.ItemContainerGenerator.ContainerFromItem(lb.Items[i])); if (tmp != null) { if (tmp.IsSelected) tmp.Visibility = System.Windows.Visibility.Visible; else tmp.Visibility = System.Windows.Visibility.Collapsed; } } } } } <Window x:Class="WpfApplication2.MainWindow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" Title="MainWindow" Height="350" Width="525" > <Grid> <ListBox Name="lb" SelectionChanged="lb_SelectionChanged" IsSynchronizedWithCurrentItem="True" > <ListBox.ItemTemplate > <DataTemplate> <StackPanel Orientation="Vertical"> <TextBlock Name="tb1" Text="whatever"/> </StackPanel> </DataTemplate> </ListBox.ItemTemplate> </ListBox> </Grid> </Window> 解决方法
我相信它是因为你使用了ItemContainerGenerator.ContainerFromItem.
ListBox默认使用VirtualizingStackPanel.因此,尚未创建加载窗口时不在屏幕上的项目.将它们设置为Collapsed后,一旦它们被带回屏幕就无效. 您可以通过更改窗口的初始高度来稍微玩一下.如果将其设置为550左右,则按预期工作.如果将其设置为150左右,您将看到很多元素仍然可见. 如果您不想拥有那么多元素,那么您可以做的一件事就是更改ItemsPanel. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |