簡體   English   中英

從列表框的ScrollInfo獲取有效值

[英]Getting valid values from ScrollInfo of a 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 ,但是我仍然得到相同的結果。

此行為由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

在第一個示例中,您將按項目滾動。 您有七個項目,因此ExtentHeight為7,可見的項目為3,因此ViewportHeight為3。

在第二個示例中,您按像素滾動,因此ExtentHeight是所有項目的總高度,視口高度是scrollviewver的高度

故事的寓意是,在某些情況下,您不想度量所有項目的大小,因為它可能會對性能產生負面影響。 尤其是在虛擬化元素時。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM