我可以通過編程設置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. 設置DataGridView的滾動條位置
- 2. 設置一個滾動條的位置
- 3. 設置div滾動條位置
- 4. 滾動條位置
- 5. jQuery UI:設置滑動條滾動條的位置
- 6. 滾動窗格設置滾動位置
- 7. 設置滾動位置
- 8. 根據滾動條位置保持div的滾動位置
- 9. 如何使用滾動條重置滾動條內的滾動條位置?
- 10. WPF滾動條位置
- 11. Android AlertDialog滾動條位置
- 12. 默認滾動條位置
- 13. 計算滾動條位置
- 14. 更改滾動條位置
- 15. Highchart滾動條位置
- 16. 固定滾動條位置
- 17. 無限滾動滾動條位置跳
- 18. 重置WPF Datagrid滾動條位置
- 19. Xceed DataGrid重置滾動條位置
- 20. 設置列表框的滾動位置
- 21. 如何設置UIScrollView的滾動位置?
- 22. 根據滾動設置div的位置
- 23. 獲取ListView中滾動條的位置(不是位置條目)
- 24. 獲取/設置超細水稻的滾動條位置
- 25. WPF:確定/設置垂直滾動條的位置
- 26. 如何更改設置位置的滾動條軌道顏色?
- 27. 如何在VB.NET中設置垂直滾動條的位置?
- 28. 在選擇框的特定位置上設置滾動條
- 29. 設置瀏覽器滾動條的大拇指位置
- 30. 你如何設置滾動條的位置
這對我很好。 – 2010-09-23 17:24:32