如何防止WPF列表框滚动到最后一项?

时间:2014-07-17 09:11:15

标签: wpf listbox scroll

我有一个列表框,显示了相同大小的主题列表。列表框显示了一列带有垂直滚动条的项目。 目前,您可以滚动浏览最后一个项目,以便列表中有1个空白区域(有7个项目的空间,当我滚动到底部时,我会看到6个项目,还有一个空白区域,正好还有1个项目)。 / p>

如何强制滚动条不滚动到最后一项?

1 个答案:

答案 0 :(得分:0)

我找到了解决方法。 就我所见,这不是填充和边距问题。

我所做的是为ScrollViewer创建一个行为,我处理ScroolChanged。

行为准则:

class ScrollViewerRestrictedScrollBehavior : Behavior<ScrollViewer>
{

    protected override void OnAttached()
    {
        base.OnAttached();
        AssociatedObject.ScrollChanged += AssociatedObject_ScrollChanged;
    }

    void AssociatedObject_ScrollChanged(object sender, ScrollChangedEventArgs e)
    {
        if (e.VerticalOffset >= MaxItemCount)
        {
            AssociatedObject.ScrollToVerticalOffset(JumpToItemCount);
        }
    }



    public double MaxItemCount
    {
        get { return (double)GetValue(MaxItemCountProperty); }
        set { SetValue(MaxItemCountProperty, value); }
    }

    // Using a DependencyProperty as the backing store for MaxItemCount.  This enables animation, styling, binding, etc...
    public static readonly DependencyProperty MaxItemCountProperty =
        DependencyProperty.Register("MaxItemCount", typeof(double), typeof(ScrollViewerRestrictedScrollBehavior), new UIPropertyMetadata(0d));





    public double JumpToItemCount
    {
        get { return (double)GetValue(JumpToItemCountProperty); }
        set { SetValue(JumpToItemCountProperty, value); }
    }

    // Using a DependencyProperty as the backing store for JumpToItemCount.  This enables animation, styling, binding, etc...
    public static readonly DependencyProperty JumpToItemCountProperty =
        DependencyProperty.Register("JumpToItemCount", typeof(double), typeof(ScrollViewerRestrictedScrollBehavior), new UIPropertyMetadata(0d));


}
来自xaml的代码用于使用它(注意我使用非常接近6的值,因此没有看到垂直滚动条中有一个小的跳转) - 这是ListBox样式的一部分:

<ScrollViewer Focusable="false" Padding="{TemplateBinding Padding}" 
  Template="{StaticResource landmarksScrollViewerControlTemplate}" >
      <ItemsPresenter SnapsToDevicePixels="{TemplateBinding SnapsToDevicePixels}"/>
        <i:Interaction.Behaviors>
          <ModuleBehaviors:ScrollViewerRestrictedScrollBehavior MaxItemCount="5.99" JumpToItemCount="5.97" />
        </i:Interaction.Behaviors>
</ScrollViewer>
相关问题