簡體   English   中英

WP7 - 在外部ScrollViewer中滾動ListBox

[英]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方法不起作用。 所以我需要使用ScrollViewerScrollToVerticalOffset方法。

當用戶單擊應用程序欄上的按鈕時,我將新項添加到綁定到ListBoxObservableCollection 如何計算要傳遞給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.

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