组合框的虚拟滚动选项

时间:2018-03-09 10:19:34

标签: wpf combobox ui-virtualization

我需要在视图中显示可见项而不是显示组合框控件中的所有行。 在滚动时,我们需要加载下一个可见项目。

我该怎么做?另外,我如何确保它是否实际加载?

示例示例:

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>

1 个答案:

答案 0 :(得分:0)

您需要做几件事。首先,让我们清理您的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>

接下来,我们需要处理滚动事件,以便在我们强制滚动查看器更改时同时跳过3项,同时防止递归。

    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
    }