6

我想自动在列表视图中显示所选项目(不滚动就不可能显示所有项目)。

this.listView.SelectedIndex = 999;当然选择一个项目,但它不显示它。

我可以用什么来自动显示它?

亲切的问候,杰夫

4

4 回答 4

10

你可以这样做:-

listview.ScrollIntoView(listview.SelectedItem);

将 WPF ListBox 滚动到视图模型中代码中设置的 SelectedItem

于 2015-08-26T09:19:38.993 回答
1

看看这个:
Scroll WPF Listview to specific line

于 2009-07-18T18:28:18.197 回答
0

安装一个 nuget 包System.Windows.Interactivity.WPF,创建一个如下所示的类:

public class ScrollToSelectedListBoxItemBehaviour: Behavior<ListBox>
{
    protected override void OnAttached()
    {
        base.OnAttached();
        AssociatedObject.SelectionChanged += AssociatedObjectOnSelectionChanged;
        AssociatedObject.IsVisibleChanged += AssociatedObjectOnIsVisibleChanged;
    }

    protected override void OnDetaching()
    {
        AssociatedObject.SelectionChanged -= AssociatedObjectOnSelectionChanged;
        AssociatedObject.IsVisibleChanged -= AssociatedObjectOnIsVisibleChanged;
        base.OnDetaching();
    }

    private static void AssociatedObjectOnIsVisibleChanged(object sender, DependencyPropertyChangedEventArgs e)
    {
        ScrollIntoFirstSelectedItem(sender);
    }

    private static void AssociatedObjectOnSelectionChanged(object sender, SelectionChangedEventArgs e)
    {
        ScrollIntoFirstSelectedItem(sender);
    }

    private static void ScrollIntoFirstSelectedItem(object sender)
    {
        if (!(sender is ListBox listBox)) 
            return;
        var selectedItems = listBox.SelectedItems;
        if (selectedItems.Count > 0)
            listBox.ScrollIntoView(selectedItems[0]);
    }
}

将此行为类添加到 xaml:

<ListView ItemsSource="{Binding Items}">
    <i:Interaction.Behaviors>
        <behaviors:ScrollToSelectedListBoxItemBehaviour />
    </i:Interaction.Behaviors>
</ListView>
于 2020-01-31T09:44:09.083 回答
-1

这可能会对您有所帮助,我不确定它是否是您正在寻找的东西,但它会将所选项目带入视图并在必要时为您滚动到它。

 int selectedIndex = listView.Items.IndexOf((listView.SelectedItems[0]))

 listView.Items[selectedIndex].EnsureVisible();
于 2010-06-18T09:39:27.107 回答