[英]WP7 - Scrolling ListBox in external ScrollViewer
我的應用程序中有以下頁面布局:
<Grid x:Name="ContentPanel"
Grid.Row="1">
<ScrollViewer x:Name="ScrollViewer1"
MaxHeight="600"
VerticalAlignment="Top"
HorizontalAlignment="Stretch">
<StackPanel x:Name="StackPanel1" >
<TextBlock x:Name="TextBlock1" />
<toolkit:ListPicker x:Name="ListPicker1" />
<TextBlock x:Name="TextBlock2" />
<TextBox x:Name="TextBlock3" />
<TextBlock x:Name="TextBlock4" />
<StackPanel x:Name="StackPanel2" >
<TextBlock x:Name="TextBlock5" />
<Image x:Name="Image1"/>
</StackPanel>
<ListBox x:Name="ListBox1">
<!--Customize the ListBox template to remove the built-in ScrollViewer-->
<ListBox.Template>
<ControlTemplate>
<ItemsPresenter />
</ControlTemplate>
</ListBox.Template>
<ListBox.ItemTemplate>
<DataTemplate>
<!-- .... -->
</DataTemplate>
</ListBox.ItemTemplate>
<ListBox.ItemContainerStyle>
<Style TargetType="ListBoxItem">
<Setter Property="HorizontalContentAlignment"
Value="Stretch" />
</Style>
</ListBox.ItemContainerStyle>
</ListBox>
</StackPanel>
</ScrollViewer>
</Grid>
我添加了一個外部ScrollViewer
而不是使用ListBox
,因為沒有它, ListBox
上面的東西占用了太多空間而沒有留下足夠的空間來查看ListBox
內容。
現在,問題是如果我在ListBox
的末尾添加一個項目, ScrollIntoView
方法不起作用。 所以我需要使用ScrollViewer
的ScrollToVerticalOffset
方法。
當用戶單擊應用程序欄上的按鈕時,我將新項添加到綁定到ListBox
的ObservableCollection
。 如何計算要傳遞給ScrollViewer.ScrollToVerticalOffset
的值?
謝謝你的幫助!
您可以找到ListBox生成的容器來托管您的元素。 擁有此容器后,您可以找到相對於scrollviewer的位置:
var newItem = // the item you just added to your listbox
// find the ListBox container
listBox.UpdateLayout()
var element = listBox.ItemContainerGenerator.ContainerFromItem(newItem) as FrameworkElement;
// find its position in the scroll viewer
var transform = element.TransformToVisual(ScrollViewer);
var elementLocation = transform.Transform(new Point(0, 0));
double newVerticalOffset = elementLocation.Y + ScrollViewer.VerticalOffset;
// scroll into view
ScrollViewer.ScrollToVerticalOffset(newVerticalOffset);
希望有所幫助
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.