WPF ScrollViewer - 滚动到第一个不可见项目

问题描述 投票:0回答:1

是否可以将ScrollViewer自动滚动到Content中的第一个不可见元素?

让我更好地解释一下,在我的项目中,我有一个按钮列表,包含在 ScrollViewer 中:
List of Buttons

我想知道当用户单击最后一个可见按钮(在本例中是 b10 和 b11 之间的一个)时,ScrollViewer 是否可以自动滚动以显示这些按钮之后的按钮。

c# wpf xaml scrollbar
1个回答
0
投票

您可以通过

AttachedProperties
来实现它。

这是

ScrollViewerAttachedProperty

的代码
public static class ScrollViewerAttachedProperty
{
    public static readonly DependencyProperty ScrollToClickProperty = DependencyProperty.RegisterAttached("ScrollToClick", typeof(bool), typeof(ScrollViewerAttachedProperty), new PropertyMetadata(false, ScrollToClickChangedCallback));

    public static void SetScrollToClick(DependencyObject element, bool value)
    {
        element.SetValue(ScrollToClickProperty, value);
    }
    public static bool GetScrollToClick(DependencyObject element)
    {
        return (bool)element.GetValue(ScrollToClickProperty);
    }

    private static void ScrollToClickChangedCallback(DependencyObject d, DependencyPropertyChangedEventArgs e)
    {
        var element = d as UIElement;

        if (element == null)
            throw new Exception("Attached property must be used with UIElement.");

        if ((bool)e.NewValue)
            element.PreviewMouseDown += Element_PreviewMouseDown;
        else
            element.PreviewMouseDown -= Element_PreviewMouseDown;
    }

    private static void Element_PreviewMouseDown(object sender, MouseButtonEventArgs e)
    {
        if (sender is ScrollViewer scrollViewer)
        {
            var item = (FrameworkElement)e.Source;
            if (item.GetType() != typeof(ScrollViewer))
            {
                var point = item.TranslatePoint(new Point(0, e.GetPosition(scrollViewer).Y), scrollViewer);

                scrollViewer.ScrollToVerticalOffset(point.Y - (item.ActualHeight * 2));
            }
        }
    }
}

如您所见,我在

PreviewMouseDown
中使用
ScrollViewer
事件,将
ScrollViewer
垂直滚动到所需位置。

并且在

XAML
中你可以像这样使用它

<ScrollViewer local:ScrollViewerAttachedProperty.ScrollToClick="True">

下次提问时,请提供

Minimal, Reproducible Example

© www.soinside.com 2019 - 2024. All rights reserved.