2012-08-24 32 views
0

我有一个包含20-50项的列表框。所有项目必须按唯一标识进行排序。 应用排序后,我的列表框在顶部滚动。如何防止呢? 排序功能如何在添加/删除项目时保持listboxitem的位置?

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); 
      } 
     } 
     } 
    } 
+0

您的使用ScollIntoView(项目),如果你发现你想要的东西。或者从ScrollViewer获取ActualHeight –

回答

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(); 
} 
0

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

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

我试过了,没有任何反应。 – SevenDays

+0

你在调用你的排序函数后试过了吗? –

+0

是的,我试过了。当我在顶部调用sort函数列表滚动时,什么也没有发生。 – SevenDays

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(); 
+0

在WP7列表框上没有IndexFromPoint方法 – SevenDays

0

使用此功能

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; 
    } 

使用此功能提取从列表框的ScrollViewer滚动到新的项目列表:

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]); 
    } 

注:与偏移值,直到你玩获得期望的结果。希望它可以帮助

相关问题