我需要在视图中显示可见项,而不是在组合框控件中显示所有行。在滚动时,我们需要加载下一个可见项。
我该怎么做呢?另外,我如何确保它是否被虚拟加载?
示例:
public List<string> items = new List<string>();
public MainWindow()
{
InitializeComponent();
DataContext = this;
for (int i = 0; i < 100000; i++)
{
items.Add("item"+ i.ToString());
}
combo.ItemsSource = items;
}前端:
<Grid>
<StackPanel>
<ComboBox x:Name="combo" Width="150" HorizontalAlignment="Left" Margin="10,10,0,10" VirtualizingPanel.IsVirtualizing="True" />
</StackPanel>
</Grid> <ComboBox x:Name="combo" Height="100" Width="150" ScrollViewer.HorizontalScrollBarVisibility="Disabled"
ScrollViewer.CanContentScroll="True" HorizontalAlignment="Left" Margin="10,10,0,10"
VirtualizingStackPanel.IsVirtualizing="True" VirtualizingStackPanel.VirtualizationMode ="Recycling" >
<ComboBox.ItemsPanel>
<ItemsPanelTemplate>
<VirtualizingStackPanel IsVirtualizing="True"
VirtualizationMode="Recycling" />
</ItemsPanelTemplate>
</ComboBox.ItemsPanel>
</ComboBox>发布于 2018-03-12 22:54:30
有几件事你需要做。首先,让我们清理ComboBox并订阅ScrollViewer.ScrollChanged事件。您的许多ComboBox属性在默认情况下已经设置好了,所以我们可以删除它们。我们还可以设置MaxDropDownHeight来指定一次显示多少项。下面是它应该是什么样子的。
<ComboBox x:Name="combo" ScrollViewer.ScrollChanged="combo_ScrollChanged" MaxDropDownHeight="70" Height="100" Width="150" HorizontalAlignment="Left" Margin="10,10,0,10">
<ComboBox.ItemsPanel>
<ItemsPanelTemplate>
<VirtualizingStackPanel/>
</ItemsPanelTemplate>
</ComboBox.ItemsPanel>
</ComboBox>接下来,我们需要处理scroll事件,以便跳过3个项目,同时防止在强制scrollviewer更改时出现递归。
bool scrolling = false;//Used to prevent recursion
private void combo_ScrollChanged(object sender, ScrollChangedEventArgs e)
{
ComboBox cb = (ComboBox)sender; //Get the sending ComboBox
ScrollViewer sv = cb.Template.FindName("DropDownScrollViewer", cb) as ScrollViewer; //Find the Comboxes ScrollViewr
//If scrolling down
if (e.VerticalChange < 0 && !scrolling)
{
scrolling = true; //Set to true to prevent recursion
sv.ScrollToVerticalOffset(e.VerticalOffset - 2);//Scroll an extra 2 spaces up
return; //Exit
}
//If scrolling up
if (e.VerticalChange > 0 && !scrolling)
{
scrolling = true; //Set to true to prevent recursion
sv.ScrollToVerticalOffset(e.VerticalOffset + 2);//Scroll an extra 2 spaces down
return; //Exit
}
if (scrolling) { scrolling = false; } //Set to false to allow offsets
}https://stackoverflow.com/questions/49191495
复制相似问题