ListBoxのスクロールバーの位置を設定する
-
03-07-2019 - |
質問
WPF ListBoxスクロールバーの位置をプログラムで設定できますか?デフォルトでは、中央に配置します。
解決
ListBoxの垂直スクロールバーを移動するには、次の手順を実行します。
- リストボックスに名前を付けます(x:Name =" myListBox")
- ウィンドウのLoadedイベントを追加(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);
}
}
}
他のヒント
Dim cnt as Integer = myListBox.Items.Count
Dim midPoint as Integer = cnt\2
myListBox.ScrollIntoView(myListBox.Items(midPoint))
または
myListBox.SelectedIndex = midPoint
中央のアイテムを表示するか選択するかによって異なります。
Zamboniのビットコードを変更し、位置計算を追加しました。
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));
ListBoxにそれがあるとは思わないが、ListViewには EnsureVisible メソッドは、アイテムが表示されることを確認するために必要な場所にスクロールバーを移動します。
所属していません StackOverflow