How to bring into view last added list view item in WPF ListView
Asked Answered
D

1

6

I am using a view model to bind to the list view. Every time I add an item in the view model internal observable collection, I trigger an LastIndex property with the list.Count-1. The list view is bound to this LastIndex proeprty of VM and the listview correctly selects the last item added to the view. Unfortunately, the view is not able to scroll the last added item into view.

I tried setting IsSynchronizedWithCurrentItem = "True" on list view markup, but it did not help.

This is the markup I am using

<ListView ItemsSource="{Binding Path=Status.Messages}" 
         SelectedIndex="{Binding Path=Status.LastIndex, Mode=OneWay}"
         ScrollViewer.HorizontalScrollBarVisibility="Hidden" 
         ScrollViewer.VerticalScrollBarVisibility="Auto"
         HorizontalAlignment="Stretch" 
         Height="60" 
         IsSynchronizedWithCurrentItem="True" >
    <ListView.Resources>
        <Style TargetType="{x:Type GridViewColumnHeader}">
            <Setter Property="Visibility" Value="Collapsed" />
        </Style>
    </ListView.Resources>
    <ListView.View>
        <GridView AllowsColumnReorder="False" >
            <GridViewColumn>
                <GridViewColumn.CellTemplate>
                    <DataTemplate>
                        <TextBlock Text="{Binding Path=.}" FontWeight="Thin" />
                    </DataTemplate>
                </GridViewColumn.CellTemplate>
            </GridViewColumn>
        </GridView>
    </ListView.View>
    <ListView.
</ListView>

Any help in this regard will be greatly appreciated

Darcidarcia answered 12/11, 2010 at 19:22 Comment(0)
A
15

You need to call ScrollIntoView:

list.ScrollIntoView(list.Items[list.Items.Count - 1]);

http://msdn.microsoft.com/en-us/library/system.windows.controls.listbox.scrollintoview.aspx

EDIT:

And here's a way to do it in XAML:

http://michlg.wordpress.com/2010/01/16/listbox-automatically-scroll-currentitem-into-view/

Andean answered 12/11, 2010 at 19:32 Comment(1)
I was going to do this in XAML because it's the most right way for MVVM but that is just too much stuff to bother. I'm surprised this is not just a property you have to set to true or false depending on if you want it to keep the latest addition in focus or not.Microbicide

© 2022 - 2024 — McMap. All rights reserved.