C# 添加/删除项目时如何保持listboxitem的位置?
我有一个包含20-50个项目的列表框。所有项目必须按唯一id排序。 应用排序后,我的列表框在顶部滚动。如何预防? 排序函数C# 添加/删除项目时如何保持listboxitem的位置?,c#,windows-phone-7,listbox,scroll,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
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);
}
}
}
}
publicstaticvoid排序(IList源代码,Func选择器){
对于(int i=source.Count-1;i>=0;i--){
对于(int j=1;j 0){
来源。移除(o1);
来源.插入(j,o1);
}
}
}
}
要将列表框焦点设置为列表中的最后一项,请使用以下表达式
this.ListBox1.SelectedIndex = this.ListBox1.Items.Count - 1;
这适用于Windows7。我没有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();
使用此函数从列表框中提取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;
}
注意:播放偏移值,直到获得所需的结果。希望它有帮助只有这样才有帮助
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();
}
在WP7列表框上没有IndexFromPoint方法是的,我在之后尝试过。当我调用排序函数时,什么也没发生。列表框在顶部滚动。如果您找到想要的项目,您可以使用ScollIntoView(项目)。或者从ScrollViewer获取实际高度
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();
}