我有書籤列表,當我點擊一個書籤,另一個頁面加載一個listA由幾個項目組成。如何將ListBox的項目設置爲頂部?
現在假設我點擊一個書籤,它指向listA的項目索引100 ...另一個listA打開,我設法將listA的SelectedIndex設置爲100,這是列表中的某處不可見。
問題是,SelectedIndex被設置爲100,但該列表仍然顯示頂部最上面的項目。
- 如何在加載內容時在頂部設置項目編號100?
我有書籤列表,當我點擊一個書籤,另一個頁面加載一個listA由幾個項目組成。如何將ListBox的項目設置爲頂部?
現在假設我點擊一個書籤,它指向listA的項目索引100 ...另一個listA打開,我設法將listA的SelectedIndex設置爲100,這是列表中的某處不可見。
問題是,SelectedIndex被設置爲100,但該列表仍然顯示頂部最上面的項目。
工程與ScrollViewer.ScrollToVerticalOffset方法
步驟一,呼叫加載的事件清單A
<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;
}
而且它與 「利斯塔」(替換利斯塔你的ListBox的名稱)
ListBox真的很痛苦(特別是對於複雜的數據模型和虛擬化)。您應該使用此解決方法:
listbox.SelectedIndex = 1000; //I mean index of the last item
listbox.UpdateLayout();
listbox.SelectedIndex = 100;
listbox.UpdateLayout();
希望這有助於
我不知道我是否正確地理解你的問題。但是,如果你只是想在列表框項目的頂部設置一個項目,然後我會做..
listbox.Items.Insert(0,「東西);
或
使用LINQ訂購他們
listbox.Items.OrderBy( 「東西」);完美
當我檢查了listA的的selectedIndex使用MessageBox(),它顯示,讓說100.因此,我認爲SelectedIndex的值屬性設置爲一個正確的值。或者,可能是我做錯了什麼。另請閱讀我與這個問題有關的其他問題:http://stackoverflow.com/questions/10094524/selectedlistindex-property-of-a-databound-listbox-cannot-be-set-why – wafers 2012-04-11 16:50:38