从ListBox的ScrollInfo获取有效值

时间:2015-03-06 14:30:34

标签: c# wpf listbox

我有一个ListBox,我面临的问题是尝试从IScrollInfo对象获取有效值。

我知道从将ListBox上的MaxHeight设置为150,ViewportHeight应该大约为这个大小,而整个高度是两倍大,所以ExtentHeight应该是大约300.

我从以下地址获得以下数值:
_scrollInfo.ExtentHeight = 13
_scrollInfo.ViewportHeight = 7
_scrollInfo.VerticalOffset = varying but 1-6

来自的价值:
UIElement scrollable = _scrollInfo as UIElement;
似乎是正确的。
scrollable.RenderSize.Height = 146大致正确。

我想知道的是:

首次加载我的ListBox控件时,它将绑定到空ObservableCollection。直到稍后才添加项目。可能是IScrollInfo对象在ListBox为空时保留这些初始值吗?

IScrollInfo对象的另一件事是VirtualizingStackPanel这可能与此有关吗?

[编辑]
我们尝试将VirtualizingStackPanel更改为StackPanel,但我仍然得到相同的结果。

1 个答案:

答案 0 :(得分:3)

此行为由ScrollViewer.CanContentScroll="True"提供 它基本上说,你不能按像素滚动,只能按项目滚动。

考虑这个例子:

private void ScrollViewer_ScrollChanged(object sender, ScrollChangedEventArgs e)
{
    var scrollViewer = (ScrollViewer) sender;
    Trace.WriteLine(string.Format("ExtentHeight: {0}, ViewportHeight : {1}, VerticalOffset : {2}",
        scrollViewer.ExtentHeight, scrollViewer.ViewportHeight, scrollViewer.VerticalOffset));
}


<ScrollViewer Height="150" ScrollChanged="ScrollViewer_ScrollChanged" CanContentScroll="True">
    <VirtualizingStackPanel>
        <Rectangle Height="40" Margin="5" Fill="Red" />
        <Rectangle Height="40" Margin="5" Fill="Green" />
        <Rectangle Height="40" Margin="5" Fill="Blue" />
        <Rectangle Height="40" Margin="5" Fill="Red" />
        <Rectangle Height="40" Margin="5" Fill="Green" />
        <Rectangle Height="40" Margin="5" Fill="Blue" />
        <Rectangle Height="40" Margin="5" Fill="Red" />
    </VirtualizingStackPanel>
</ScrollViewer>

你得到以下输出:

ExtentHeight: 7, ViewportHeight : 3, VerticalOffset : 0   
ExtentHeight: 7, ViewportHeight : 3, VerticalOffset : 1
ExtentHeight: 7, ViewportHeight : 3, VerticalOffset : 2   

但是当你设置CanContentScroll="False"时:

ExtentHeight: 350, ViewportHeight : 150, VerticalOffset : 3,01724137931035
ExtentHeight: 350, ViewportHeight : 150, VerticalOffset : 6,03448275862069
ExtentHeight: 350, ViewportHeight : 150, VerticalOffset : 9,05172413793104
ExtentHeight: 350, ViewportHeight : 150, VerticalOffset : 12,0689655172414
ExtentHeight: 350, ViewportHeight : 150, VerticalOffset : 15,0862068965517
ExtentHeight: 350, ViewportHeight : 150, VerticalOffset : 18,1034482758621
ExtentHeight: 350, ViewportHeight : 150, VerticalOffset : 21,1206896551724

在第一个示例中,您按项目滚动。你有7个项目,所以ExtentHeight是7个,可见3个项目,所以ViewportHeight是3个。

在第二个示例中,您按像素滚动,因此ExtentHeight是所有项目的总高度,视口高度是scrollviewver的高度

故事的道德是,在某些情况下,您不想测量所有项目的大小,因为它可能会产生负面的性能影响。特别是在虚拟化元素时就是这种情况。

相关问题