有没有一种简单的方法让ListView自动滚动到最近添加的项目而不必在后面的代码中编写任何代码?

skq*_*ada 5 wpf listview scroll

我有一个ListView绑定到一个可观察的集合.当项目添加到可观察集合时,列表视图不会自动滚动以显示最近添加的项目.我试图坚持良好的WPF实践,并希望避免在视图的代码隐藏中编写任何代码.有没有一种简单的方法可以通过XAML或相应的Model的代码实现这一目的?

<ListView HorizontalAlignment="Center" ItemsSource="{Binding ScenarioSnippets}" Background="{x:Null}" 
                      BorderBrush="{x:Null}" BorderThickness="0" SelectionMode="Single" VerticalAlignment="Top" 
                      HorizontalContentAlignment="Center" IsSynchronizedWithCurrentItem="True">
                <ListView.ItemContainerStyle>
                    <Style TargetType="{x:Type ListViewItem}">
                        <Setter Property="Focusable" Value="False" />
                    </Style>
                </ListView.ItemContainerStyle>
                <ListView.View>
                    <GridView Selector.IsSelected="True" AllowsColumnReorder="False">
                        <GridView.Columns>
                            <GridViewColumn CellTemplate="{StaticResource ScenarioSnippetItemCellTemplate}" 
                                            HeaderContainerStyle="{StaticResource GridViewHeaderStyle}" />
                        </GridView.Columns>
                    </GridView>
                </ListView.View>
        </ListView>
Run Code Online (Sandbox Code Playgroud)

Tho*_*que 9

您可以使用混合行为:

public class AutoScrollToLastItemBehavior : Behavior<ListBox>
{
    protected override void OnAttached()
    {
        base.OnAttached();
        var collection = AssociatedObject.Items.SourceCollection as INotifyCollectionChanged;
        if (collection != null)
            collection.CollectionChanged += collection_CollectionChanged;
    }

    protected override void OnDetaching()
    {
        base.OnDetaching();
        var collection = AssociatedObject.Items.SourceCollection as INotifyCollectionChanged;
        if (collection != null)
            collection.CollectionChanged -= collection_CollectionChanged;
    }

    private void collection_CollectionChanged(object sender, NotifyCollectionChangedEventArgs e)
    {
        if (e.Action == NotifyCollectionChangedAction.Add)
        {
            ScrollToLastItem();
        }
    }

    private void ScrollToLastItem()
    {
        int count = AssociatedObject.Items.Count;
        if (count > 0)
        {
            var last = AssociatedObject.Items[count - 1];
            AssociatedObject.ScrollIntoView(last);
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

XAML:

<ListView ItemsSource="...">
    <i:Interaction.Behaviors>
        <local:AutoScrollToLastItemBehavior />
    </i:Interaction.Behaviors>
</ListView>
Run Code Online (Sandbox Code Playgroud)

(BehaviorInteraction类可以System.Windows.Interactivity.dll在Blend SDK中找到)


Aar*_*ver 2

您需要创建一个附加行为,这将使您ListView能够遵循 MVVM 范式,这就是您最终追求的目标。

可以在此处找到解决方案/示例ListBox(可以轻松修改) 。ListView