ListBox 中有多个 ListBoxItem 元素。超出ListBox高度后,默认的虚拟化机制,使界面只加载可见范围内的元素。拖动滚动条后,再加载新的元素到界面。
如果需要,可以取消列表控件的虚拟化。 VirtualizingPanel.IsVirtualizing="False"
<ListBox Name="interestedStores" Grid.Row="2" BorderThickness="1,0,1,1" d:ItemsSource="{d:SampleData ItemCount=5}"
VirtualizingPanel.IsVirtualizing="False">
<ListBox.ItemTemplate>
<DataTemplate>
<StackPanel Height="18">
<CheckBox Name="chk" Content="{Binding Name}"/>
</StackPanel>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
private void chkAll_Click(object sender, RoutedEventArgs e)
{
foreach (var item in interestedStores.Items)
{
//不关闭虚拟化,这里获取不了不可见的 ListBoxItem
var el = interestedStores.ItemContainerGenerator.ContainerFromItem(item) as ListBoxItem;
if (el != null && el is ListBoxItem)
{
ListBoxItem listBoxItem = (ListBoxItem)el;
FrameworkElement elfind = WpfHelper.FindChildByType(listBoxItem, typeof(CheckBox));
if (elfind != null)
{
((CheckBox)elfind).IsChecked = chkAll.IsChecked;
}
}
}
}