Home > Software design >  C# WPF Set ScrollViewer vertical offset at item position
C# WPF Set ScrollViewer vertical offset at item position

Time:07-30

I'm using a ScrollViewer to scroll an ItemsControl with a variable number of TextBox.

<ScrollViewer extension:ScrollViewerExtension.ScrollOffset="{Binding TotalSearchOccurence}" ScrollViewer.HorizontalScrollBarVisibility="Visible" ScrollViewer.VerticalScrollBarVisibility="Visible">
   <ItemsControl  ItemsSource="{Binding Source={StaticResource viewSource}}">
     <ItemsControl.ItemContainerStyle>
        <Style>
          <Setter Property="FrameworkElement.Margin" Value="5"/>
        </Style>
      </ItemsControl.ItemContainerStyle>
      <ItemsControl.ItemTemplate>
         <DataTemplate>
            <controls:HighlightTextBlock IsHighlightEnabled="{Binding Path=DataContext.SearchBarModel.IsVisible, RelativeSource={RelativeSource Mode=FindAncestor ,AncestorType={x:Type Window}}}" LineHightlights="{Binding Path=LineHightlights}" Text="{Binding Path=Content, Mode=OneWay}" Background="Transparent" BorderThickness="0" Foreground="{Binding Path=Color, Mode=OneWay}" FontSize="14" SelectedHighlightIndex="{Binding SelectedHighlightIndex}"/>                                      
         </DataTemplate>
      </ItemsControl.ItemTemplate>
   </ItemsControl>
 </ScrollViewer>

I want to set the vertical offset of my ScrollViewer at a specific line item position so that this item is at the top of my screen (if this item is not in the lasts positions of my ItemControl).

The different information I have is the total number of items in my ItemControl and the maximum scrollable offset of my ScrollViewer.

How can I manage to do that?

CodePudding user response:

You have to do a call to BringToView() on your UIElement.

For exemple, if you have a TextBlock contained inside your items list of an ItemsControl encapsulated in a ScrollViewer, you can just do TextBlock.BringIntoView().

  • Related