WPF ListView显示所选项目

时间:2009-07-18 18:25:26

标签: wpf listview selecteditem

我想自动在列表视图中显示所选项目(如果不滚动则无法显示所有项目。)

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

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

亲切的问候,杰夫

3 个答案:

答案 0 :(得分:1)

答案 1 :(得分:0)

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

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

 listView.Items[selectedIndex].EnsureVisible();

答案 2 :(得分: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>