【问题标题】:How to prevent a WPF listbox from scrolling past the last item?如何防止 WPF 列表框滚动到最后一项?
【发布时间】:2014-07-17 09:11:15
【问题描述】:

我有一个列表框,显示相同大小的项目列表。列表框显示带有垂直滚动条的单列项目。 目前,您可以滚动越过最后一项,以便列表中有 1 个空白空间(有 7 个项目的空间,当我滚动到底部时,我看到 6 个项目和一个空白空间,正好还有 1 个项目)。

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

【问题讨论】:

  • 您的列表框项目似乎存在一些边距/填充问题。您可以为您的列表框和您正在使用的任何样式发布一些 xaml 吗?

标签: wpf listbox scroll


【解决方案1】:

我找到了解决方案。 据我所知,这不是填充和边距的问题。

我所做的是为 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>

【讨论】:

    猜你喜欢
    • 2021-01-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-09-17
    • 1970-01-01
    相关资源
    最近更新 更多