我想实现一个包含int值的动态组合框,并在用户到达列表末尾之前动态加载新元素。
所以例如我加载列表的初始值为15,列表最初包含+ - 5元素,当用户从列表末尾到达+ - 3.元素时,它又分别向该元素添加5个元素结束或开始。
我如何存档?
答案 0 :(得分:2)
为此,您需要处理scrollViwer
Combobox
内ControlTemplate
控件的combobox
事件。
首先,编辑DropDownScrollViewer
模板:来自visual studio designer selecte> 修改模板> 编辑副本,
在生成的样式搜索ScrollChanged
并添加//..
<Border x:Name="dropDownBorder" BorderBrush="{DynamicResource {x:Static SystemColors.WindowFrameBrushKey}}" BorderThickness="1" Background="{DynamicResource {x:Static SystemColors.WindowBrushKey}}">
<ScrollViewer x:Name="DropDownScrollViewer" ScrollChanged="OnScrollChanged">
<Grid x:Name="grid" RenderOptions.ClearTypeHint="Enabled">
<Canvas x:Name="canvas" HorizontalAlignment="Left" Height="0" VerticalAlignment="Top" Width="0">
<Rectangle x:Name="opaqueRect" Fill="{Binding Background, ElementName=dropDownBorder}" Height="{Binding ActualHeight, ElementName=dropDownBorder}" Width="{Binding ActualWidth, ElementName=dropDownBorder}"/>
</Canvas>
<ItemsPresenter x:Name="ItemsPresenter" KeyboardNavigation.DirectionalNavigation="Contained" SnapsToDevicePixels="{TemplateBinding SnapsToDevicePixels}"/>
</Grid>
</ScrollViewer>
</Border>
//..
事件处理程序
combobox
现在,假设您的ObservableCollection
绑定到<ComboBox x:Name="CbBox" ItemsSource="{Binding CboxItems}" VerticalAlignment="Center" HorizontalAlignment="Center" Style="{DynamicResource ComboBoxStyle1}"/>
,就像这样:
private ObservableCollection<string> _cboxItemsCollection = new ObservableCollection<string>()
{
"0",
"1",
"2",
"3",
"4",
"5",
};
public ObservableCollection<string> CboxItems
{
get
{
return _cboxItemsCollection;
}
set
{
if (_cboxItemsCollection == value)
{
return;
}
_cboxItemsCollection = value;
OnPropertyChanged();
}
}
private void OnScrollChanged(object sender, ScrollChangedEventArgs e)
{
var scrollViewer = (ScrollViewer)sender;
if (scrollViewer.VerticalOffset == scrollViewer.ScrollableHeight)
{
for (int i = 0; i < 5; i++)
{
CboxItems.Add((CboxItems.Count+i).ToString());
}
}
}
处理程序看起来应该是这样的:
VerticalOffset
修改强>
我忘了提到滚动到顶部,当scrollViewer
的{{1}}等于0时遵循相同的原则,将负项目插入集合的顶部:
//..
if (scrollViewer.VerticalOffset == 0)
{
for (int i = 0; i < 5; i++)
{
CboxItems.Insert(0,"negaive item");
}
scrollViewer.ScrollToVerticalOffset(10);
}
//..
scrollViewer.ScrollToVerticalOffset(10);
是为了防止无限循环,因为默认情况下scrollViewer
始终滚动到顶部。