我的应用程序中有以下页面布局:
<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
the ScrollIntoView
方法不起作用。所以我需要使用ScrollViewer
's ScrollToVerticalOffset
方法。
我正在将新项目添加到ObservableCollection
这与ListBox
当用户单击应用程序栏上的按钮时。我如何计算要传递给的值ScrollViewer.ScrollToVerticalOffset
?
感谢您的帮助!
您可以找到 ListBox 生成的用于托管元素的容器。一旦你有了这个容器,你就可以找到它相对于滚动查看器的位置:
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);
希望有帮助
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)