1

我有书签列表,当我点击书签时,另一个页面加载了一个 listA 由几个项目组成。

现在假设,我点击一个书签,它指向 listA 的项目索引 100...打开另一个 listA,我设法将 listA 的 SelectedIndex 设置为 100,这是在列表下方的某个地方不可见。

问题是,SelectedIndex 设置为 100,但列表仍然显示最顶部的项目,在顶部。

  • 加载内容时,如何在顶部设置项目编号 100?
4

4 回答 4

2

与 ScrollViewer.ScrollToVerticalOffset 方法完美配合

Step I. 调用listA的Loaded事件

<ListBox Name="ListA"  Loaded="HookScrollViewer">

第二步。定义“HookScrollViewer”方法

    private void HookScrollViewer(object sender, RoutedEventArgs e)
    {
        var element = (FrameworkElement)sender;
        var scrollViewer = FindChildOfType<ScrollViewer>(element);

        if (scrollViewer == null)
            return;

        scrollViewer.ScrollToVerticalOffset(lstA.SelectedIndex);
    }

第三步。定义“FindChildOfType”方法

    public static T FindChildOfType<T>(DependencyObject root) where T : class
    {
        var queue = new Queue<DependencyObject>();
        queue.Enqueue(root);

        while (queue.Count > 0)
        {
            var current = queue.Dequeue();
            for (int i = VisualTreeHelper.GetChildrenCount(current) - 1; 0 <= i; i--)
            {
                var child = VisualTreeHelper.GetChild(current, i);
                var typedChild = child as T;
                if (typedChild != null)
                {
                    return typedChild;
                }
                queue.Enqueue(child);
            }
        }
        return null;
    }

它适用于“ListA”(将 ListA 替换为您的 ListBox 的名称)

参考:WP7 中的 ListBox 偏移量

于 2012-04-12T08:16:31.897 回答
1

ListBox 真的很让人头疼(尤其是复杂的数据模板和虚拟化)。您应该使用此解决方法:

listbox.SelectedIndex = 1000; //I mean index of the last item
listbox.UpdateLayout();
listbox.SelectedIndex = 100;
listbox.UpdateLayout();

希望这可以帮助

于 2012-04-11T16:54:07.763 回答
0

试试这个:

listBox2.TopIndex = listBox2.SelectedIndex;
于 2012-04-11T16:59:24.970 回答
0

我不确定我是否正确理解了您的问题。但是,如果您只想在列表框项目之上设置一个项目,那么我会这样做..

listbox.Items.Insert(0, "某事);

或者

使用 linq 订购它们

listbox.Items.OrderBy("something");

于 2012-04-12T03:16:33.897 回答