一般我们WPF中Combox的绑定都是下面这种写法。
XAML:
<ComboBox IsEditable="False" ItemsSource="{Binding List, Mode=OneWay, IsAsync=True}" SelectedIndex="{Binding SelectedSheetIndex, Mode=TwoWay}"> <ComboBox.ItemTemplate> <DataTemplate> <StackPanel Orientation="Horizontal"> <TextBlock Margin="2.5" Text="{Binding Name, Mode=OneTime}" /> </StackPanel> </DataTemplate> </ComboBox.ItemTemplate> </ComboBox>
后台:
private List<string> list; public List<string> List { get { return list; } set { SetProperty(ref list, value); } }
问题点:大量数据绑定时会卡顿,鼠标点击无法弹出下拉列表。
解决办法就是将ItemsPanelTemplate的值设置为VirtualizingStackPanel。它可以让UI显示1万个左右的项目。
<ComboBox IsEditable="False" ItemsSource="{Binding SheetList, Mode=OneWay, IsAsync=True}" SelectedIndex="{Binding SelectedSheetIndex, Mode=TwoWay}"> <ComboBox.ItemsPanel> <ItemsPanelTemplate> <VirtualizingStackPanel/> </ItemsPanelTemplate> </ComboBox.ItemsPanel> <ComboBox.ItemTemplate> <DataTemplate> <StackPanel Orientation="Horizontal"> <TextBlock Margin="2.5" Text="{Binding Name, Mode=OneTime}" /> </StackPanel> </DataTemplate> </ComboBox.ItemTemplate> </ComboBox>