Search code examples
c#scrollwrappanel

How to scroll automatically to a specific item in a wrappanel?


Currently i collaborate in a big software project and i got a problem with a nice feature i trying to implement.

The problem is, i dont know how to scroll automatically to a specific item which is able to be selected by some user. The wrappanel is used as an itemspaneltemplate from an itemscontrol.

The code follows for a better understanding:

<ItemsControl ItemsSource="{Binding SomeData}">
   <ItemsControl.ItemsPanel>
      <ItemsPanelTemplate>
         <WrapPanel />
      </ItemsPanelTemplate>
   </ItemsControl.ItemsPanel>
   <ItemsControl.ItemTemplate>
      <DataTemplate>
         <SomeChart DataContext="{Binding }" Focusable="True" />
      </DataTemplate>
   </ItemsControl.ItemTemplate>
</ItemsControl>

Solution

  • You mentioned an ItemsControl, most of the controls that derive from an ItemsControl have a ScrollIntoView method to scroll the Listbox/Datagrid to the currently selected item.

    For example:

    listBox1.ScrollIntoView(listBox1.SelectedIndex);
    

    or

    dataGrid1.ScrollIntoView(dataGrid1.SelectedIndex);
    

    Here's another solution for a ListView.

    Update: Listbox with Wrappanel

    <ListBox x:Name="myList">
        <ListBox.ItemsPanel>
            <ItemsPanelTemplate>
                <WrapPanel ItemHeight="150" ItemWidth="150"/>
            </ItemsPanelTemplate>
        </ListBox.ItemsPanel>
    </Listbox>