Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

like image 327
siva Avatar asked Nov 12 '10 19:11

siva


1 Answers

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/

like image 168
Jesper Larsen-Ledet Avatar answered Oct 21 '22 14:10

Jesper Larsen-Ledet