2012-08-24 34 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]); 
    } 

注:與偏移值,直到你玩獲得期望的結果。希望它可以幫助

相關問題