如何将ListBox的Item设置到顶部?

时间:2012-04-11 16:47:49

标签: c# windows-phone-7 listbox

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

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

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

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

4 个答案:

答案 0 :(得分:2)

与ScrollViewer.ScrollToVerticalOffset方法

完美配合

步骤I.调用listA的已加载事件

<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”(用ListBox的名称替换ListA)

参考:ListBox offset in WP7

答案 1 :(得分:1)

ListBox真的很痛苦(特别是对于复杂的数据模板和虚拟化)。您应该使用此解决方法:

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

希望这有帮助

答案 2 :(得分:0)

试试这个:

listBox2.TopIndex = listBox2.SelectedIndex;

答案 3 :(得分:0)

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

listbox.Items.Insert(0,“something);

使用linq订购

listbox.Items.OrderBy( “东西”);

相关问题