我可以通過編程設置WPF ListBox的滾動條的位置嗎?默認情況下,我希望它位於中心。設置ListBox的滾動條位置
9
A
回答
7
要移動在ListBox垂直滾動條執行以下操作:
- 名稱列表框(X:NAME = 「myListBox」)
- 的窗口中添加Loaded事件(加載=「Window_Loaded 「)
- 實現Loaded事件使用方法:ScrollToVerticalOffset
這裏是一個工作示例:
XAML:
<Window x:Class="ListBoxScrollPosition.Views.MainView"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Loaded="Window_Loaded"
Title="Main Window" Height="100" Width="200">
<DockPanel>
<Grid>
<ListBox x:Name="myListBox">
<ListBoxItem>Zamboni</ListBoxItem>
<ListBoxItem>Zamboni</ListBoxItem>
<ListBoxItem>Zamboni</ListBoxItem>
<ListBoxItem>Zamboni</ListBoxItem>
<ListBoxItem>Zamboni</ListBoxItem>
<ListBoxItem>Zamboni</ListBoxItem>
<ListBoxItem>Zamboni</ListBoxItem>
<ListBoxItem>Zamboni</ListBoxItem>
<ListBoxItem>Zamboni</ListBoxItem>
<ListBoxItem>Zamboni</ListBoxItem>
<ListBoxItem>Zamboni</ListBoxItem>
<ListBoxItem>Zamboni</ListBoxItem>
</ListBox>
</Grid>
</DockPanel>
</Window>
C#
private void Window_Loaded(object sender, RoutedEventArgs e)
{
// Get the border of the listview (first child of a listview)
Decorator border = VisualTreeHelper.GetChild(myListBox, 0) as Decorator;
if (border != null)
{
// Get scrollviewer
ScrollViewer scrollViewer = border.Child as ScrollViewer;
if (scrollViewer != null)
{
// center the Scroll Viewer...
double center = scrollViewer.ScrollableHeight/2.0;
scrollViewer.ScrollToVerticalOffset(center);
}
}
}
-1
我不認爲ListBox有那個,但ListViews有EnsureVisible方法將滾動條移動到所需的位置,以確保顯示一個項目。
+0
EnsureVisible是一個windows.Forms函數,問題是關於WPF。據我所知,在WPF中沒有EnsureVisible方法。 – Sam 2008-10-17 12:19:01
3
Dim cnt as Integer = myListBox.Items.Count
Dim midPoint as Integer = cnt\2
myListBox.ScrollIntoView(myListBox.Items(midPoint))
或
myListBox.SelectedIndex = midPoint
,如果你想中間的項目剛剛展示,或選擇要看。
+0
這只是將其滾動到視圖中。我需要它滾動到中心。但是,謝謝 – ScottG 2008-10-03 14:17:01
0
我只是改變了贊博尼的位代碼並添加位置計算。
var border = VisualTreeHelper.GetChild(list, 0) as Decorator;
if (border == null) return;
var scrollViewer = border.Child as ScrollViewer;
if (scrollViewer == null) return;
scrollViewer.ScrollToVerticalOffset((scrollViewer.ScrollableHeight/list.Items.Count)*
(list.Items.IndexOf(list.SelectedItem) + 1));
相關問題
- 1. 設置滾動條的位置
- 2. 設置一個滾動條的位置
- 3. 滾動窗格設置滾動位置
- 4. 設置滾動位置
- 5. 如何使用滾動條重置滾動條內的滾動條位置?
- 6. 固定滾動條位置
- 7. WPF滾動條位置
- 8. 更改滾動條位置
- 9. 計算滾動條位置
- 10. Android AlertDialog滾動條位置
- 11. 無限滾動滾動條位置跳
- 12. 重置WPF Datagrid滾動條位置
- 13. Xceed DataGrid重置滾動條位置
- 14. 如何設置UIScrollView的滾動位置?
- 15. 設置列表框的滾動位置
- 16. 根據滾動設置div的位置
- 17. WPF:確定/設置垂直滾動條的位置
- 18. 我如何首先捕捉並設置滾動條的位置?
- 19. 如何在VB.NET中設置垂直滾動條的位置?
- 20. 獲取/設置超細水稻的滾動條位置
- 21. 如何更改設置位置的滾動條軌道顏色?
- 22. HTML。將滾動條設置在確定的位置
- 23. 如何設置網頁的滾動條位置
- 24. 設置滾動條CSS
- 25. 滾動位置的動畫條
- 26. WPF - 在ItemsSource更改時重置ListBox滾動位置
- 27. 將水平滾動條位置設置到最右端
- 28. excel - vba - userform - frame - 設置滾動條位置
- 29. 在WPF DataGrid中設置垂直滾動條位置
- 30. 將div滾動條設置爲特定位置
這對我很好。 – 2010-09-23 17:24:32