添加/删除项目时如何保持listboxitem的位置?

时间:2012-08-24 22:15:45

标签: c# windows-phone-7 listbox scroll

我有一个包含20-50项的列表框。所有项目必须按唯一ID排序。 应用排序后,我的列表框滚动到顶部。怎么预防? 排序功能

public static void Sort<TSource, TValue>(IList<TSource> source, Func<TSource, TValue> selector) {
      for (int i = source.Count - 1; i >= 0; i--) {
        for (int j = 1; j <= i; j++) {
          TSource o1 = source.ElementAt(j - 1);
          TSource o2 = source.ElementAt(j);
          TValue x = selector(o1);
          TValue y = selector(o2);
          var comparer = Comparer<TValue>.Default;
          if (comparer.Compare(x, y) > 0) {
            source.Remove(o1);
            source.Insert(j, o1);
          }
        }
      }
    }

4 个答案:

答案 0 :(得分:0)

要将ListBox焦点设置为列表中的最后一项,请使用以下表达式。

this.ListBox1.SelectedIndex = this.ListBox1.Items.Count - 1;

答案 1 :(得分:0)

这适用于Windows 7.我没有WP7来测试它。

// Finds the last item on the screen
int index = listBox1.IndexFromPoint(1, listBox1.Height - 5);

// Sorting stuff...

// Set the selected index to the one we saved, this causes the box to scroll it into view
listBox1.SelectedIndex = index;
// Clear the selection
listBox1.ClearSelected();

答案 2 :(得分:0)

使用此函数从listBox中提取scrollviewer

    public ScrollViewer FindScrollViewer(DependencyObject parent)
    {
        var childCount = VisualTreeHelper.GetChildrenCount(parent);
        for (var i = 0; i < childCount; i++)
        {
            var elt = VisualTreeHelper.GetChild(parent, i);
            if (elt is ScrollViewer) return (ScrollViewer)elt;
            var result = FindScrollViewer(elt);
            if (result != null) return result;
        }
        return null;
    }

使用此功能滚动到列表中的新项目:

    private void ScrollToOnFreshLoad()
    {
        ScrollViewer scroll = FindScrollViewer(listBox);
        Int32 offset = Convert.ToInt32(scroll.VerticalOffset);

        //load new list box here

        //then do this
        listBox.ScrollIntoView(listItems[offset]);
    }

注意:使用偏移值,直到获得所需的结果。希望它有所帮助

答案 3 :(得分:0)

只有这有帮助

void loadItems(){
//load
    var t = new DispatcherTimer { Interval = TimeSpan.FromMilliseconds(1000) };
            t.Tick += delegate {
              _ScrollViewer.UpdateLayout();
              SomethingLoading = false;
              listmy.ScrollIntoView(listmy.Items[listmy.Items.Count - 10]);
            };
            t.Start();
}