如何使ScrollViewer在静态设置索引后滚动,其中包含列表



我使用Silverlight 5和c#来创建一个滚动条。

我有ListBox,我创建了一个滚动条,在滚动条里面我显示了一个项目列表,像这样:(我的代码显示了所有7个项目,但我只是想显示3个项目,不滚动,其余4个通过滚动)

        TextBlock txtblkShowStatus = null;
        ListBox lines = new ListBox();
        ScrollViewer scrollViewer = new ScrollViewer();
        scrollViewer.VerticalScrollBarVisibility = ScrollBarVisibility.Visible;
        lines.ItemsSource = param.Component.Attributes.Items;
        scrollViewer.Content = lines;
        scrollViewer.HorizontalAlignment = HorizontalAlignment.Center;
        scrollViewer.VerticalAlignment = VerticalAlignment.Center;
        scrollViewer.ScrollToVerticalOffset(3); //By this line i want to display the only 3 items (out of7).
       //I mean the other 4 items must be visible on scrolling.
        Grid.SetColumn(scrollViewer, 1);          
        childGrid.Children.Add(scrollViewer);
        txtblkShowStatus = generateTextBlock();
        lines.SelectionChanged += (o, e) =>
        {
            txtblkShowStatus.Text = lines.SelectedItem.ToString();
        };
        lines.SelectedIndex = 2; //It will display énd item in txtblkShowStatus when no clikc happens at starting.
        Grid.SetColumn(txtblkShowStatus, 2);
        childGrid.Children.Add(txtblkShowStatus); //This childGrid contain a row with 3 columns.

通过这一行scrollViewer.ScrollToVerticalOffset(3);我只想显示7个项目中的3个,我的意思是其他4个项目必须在滚动滚动条时可见。

注意:请注意,我不必使用height,我需要处理索引,因为我将静态地设置索引,它必须只显示值,直到该索引和其余值将在滚动时显示。(如果你有任何其他的想法来实现它,请解释它)

如何做到这一点?

这与rae1的建议类似,

        int index = 5; //say you want to display upto 5th element
        ListBox lines = new ListBox();
        lines.Width = 100;
        ScrollViewer scrollViewer = new ScrollViewer();
        scrollViewer.VerticalScrollBarVisibility = ScrollBarVisibility.Visible;
        for (int i = 0; i < 5; i++)
        {
            lines.Items.Add(new ListBoxItem
                        {
                           Content = i.ToString()
                        });
        }
        foreach (ListBoxItem lv in lines.Items)
        {
            lv.Height = 10;
        }
        scrollViewer.Height = index * 10;
        scrollViewer.Content = lines;
        Grid.SetColumn(scrollViewer, 1);
        childGrid.Children.Add(scrollViewer);

ScrollToVerticalOffset方法不做您想用它做的事情。它只会在需要的时候滚动。在您的例子中,您可以看到所有7个元素,因为空格允许您看到它们。

如果您想只显示前三个项目,您需要修改ScrollViewerHeight属性并将其设置为合适的值。

如果你有7个项目,并且每个项目的高度是10px,并且ScrollViewer的高度是100px,则不需要滚动,因为所有项目都可以在给定的空间中安装。但是,如果您将高度更改为30px,那么ScrollViewer只有30px来显示70px的内容大小,因此您需要滚动以查看其余项目,实现您想要的效果。