سؤال

هل يمكنني تعيين موضع شريط التمرير الخاص بـ WPF ListBox برمجيًا؟بشكل افتراضي، أريده أن يذهب إلى المركز.

هل كانت مفيدة؟

المحلول

لتحريك شريط التمرير العمودي في ListBox قم بما يلي:

  1. قم بتسمية مربع القائمة الخاص بك (x:Name="myListBox")
  2. إضافة حدث تم تحميله للنافذة (Loaded="Window_Loaded")
  3. تنفيذ الحدث المحمل باستخدام الطريقة: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>

ج #

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

وهذا يعتمد على إذا كنت ترغب في البند الأوسط أظهرت فقط، أو اختيار.

ولقد تغيرت مجرد رمز قليلا من زمبوني وأضاف حساب الموقف.

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));

وأنا لا أعتقد مربعات سرد لها ذلك، ولكن ListViews يكون في EnsureVisible الطريقة التي يتحرك شريط التمرير إلى المكان اللازمة من أجل التأكد من يظهر عنصر.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top