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

倖福魔咒の 提交于 2019-12-06 01:57:02

问题


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


回答1:


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/



来源:https://stackoverflow.com/questions/4168275/how-to-bring-into-view-last-added-list-view-item-in-wpf-listview

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!