如何移动到WPF列表框的顶部?

mxg2im7a  于 2023-05-30  发布在  其他
关注(0)|答案(1)|浏览(217)

我在一个.xaml文件中有一个可滚动的ListBox,它绑定到一些数据--一个视图模型中的可观察集合。
当新数据添加到集合中时,该数据将添加到ListBox的顶部。当列表框包含大量数据时,我向下滚动列表框,新数据被添加到它的顶部,但我看不到它,除非我使用滚动条滚动到顶部。如何在每个新项目添加到Observable集合后自动滚动到顶部?
WPF代码:

<ListBox Grid.Row="2"
                 Grid.Column="0"
                 ItemsSource="{Binding BagItems}"
                 ItemTemplateSelector="{StaticResource BagItemTemplateSelector}"
                 Grid.ColumnSpan="5"
                 Foreground="{DynamicResource DarkerGreyBrush}"
                 Background="{DynamicResource LightestGreyBrush}"
                 FontWeight="Medium"
                 HorizontalContentAlignment="Stretch"
                 ItemContainerStyle="{DynamicResource ListBoxContainerStyle}"
                 SelectedItem="{Binding SelectedItem}" 
                 ScrollViewer.HorizontalScrollBarVisibility="Disabled"
                 KeyDown="ListBox_KeyDown" ManipulationBoundaryFeedback="ListBox_ManipulationBoundaryFeedback">
            <i:Interaction.Behaviors>
                <behaviours:ListBoxSelectionModeOverrideBehaviour SupressKeyEvents="{Binding DialogController.DialogAvailable}" />
            </i:Interaction.Behaviors>
        </ListBox>

查看模型C#代码:

if (shoppingBagItem != null)
{
    this.TryInvokeOnUiThread(() =>
    {
        this.BagItems.Insert(0, shoppingBagItem);
        this.SelectedItem = shoppingBagItem;
    });
}
50few1ms

50few1ms1#

下面的Behavior类将自动将ListBoxSelectedItem滚动到视图中。

public class perListBoxHelper : Behavior<ListBox>
{
    protected override void OnAttached()
    {
        base.OnAttached();
        AssociatedObject.SelectionChanged += AssociatedObject_SelectionChanged;
    }

    protected override void OnDetaching()
    {
        base.OnDetaching();
        AssociatedObject.SelectionChanged -= AssociatedObject_SelectionChanged;
    }

    private static void AssociatedObject_SelectionChanged(object sender, SelectionChangedEventArgs e)
    {
        var listBox = sender as ListBox;

        if (listBox == null)
        {
            return;
        }

        Action action = () =>
        {
            var selectedItem = listBox.SelectedItem;

            if (selectedItem != null)
            {                    
                listBox.ScrollIntoView(selectedItem);
            }
        };

        listBox.Dispatcher.BeginInvoke(action, DispatcherPriority.ContextIdle);
    }
}

使用说明

<ListBox ... >
    <i:Interaction.Behaviors>
        <vhelp:perListBoxScrollSelecionIntoViewBehavior />
    </i:Interaction.Behaviors>
</ListBox>

关于我的blog post的更多细节。

相关问题