MVVM WPF中我的ScrollViewer的OnScrollChanged事件

时间:2019-05-07 12:05:58

标签: wpf mvvm scrollviewer

我希望使用附加属性来处理ScrollViewer的ScrollChanged事件。此刻,事件和逻辑在后面的UI代码中处理,这显然与MVVM有点冲突。我想知道是否有人对如何使用附加属性执行此操作有任何想法?我发现的唯一资源似乎很漫长。这是我目前的代码:

XAML:

<ScrollViewer x:Name="MyScroller" HorizontalScrollBarVisibility="Auto" VerticalScrollBarVisibility="Visible" ScrollChanged="MyScroller_OnScrollChanged">

隐藏的用户界面代码:

private void MyScroller_OnScrollChanged(object sender, ScrollChangedEventArgs e) {
            var scrollViewer = sender as ScrollViewer;


            if ((Math.Abs(e.ExtentHeightChange) < 0) && (Math.Abs(e.ExtentWidthChange) < 0)) return;
            var xMousePositionOnScrollViewer = Mouse.GetPosition(scrollViewer).X;
            var yMousePositionOnScrollViewer = Mouse.GetPosition(scrollViewer).Y;
            var offsetX = e.HorizontalOffset + xMousePositionOnScrollViewer;
            var offsetY = e.VerticalOffset + yMousePositionOnScrollViewer;

            var oldExtentWidth = e.ExtentWidth - e.ExtentWidthChange;
            var oldExtentHeight = e.ExtentHeight - e.ExtentHeightChange;

            var relx = offsetX / oldExtentWidth;
            var rely = offsetY / oldExtentHeight;

            offsetX = Math.Max(relx * e.ExtentWidth - xMousePositionOnScrollViewer, 0);
            offsetY = Math.Max(rely * e.ExtentHeight - yMousePositionOnScrollViewer, 0);



            scrollViewer.ScrollToHorizontalOffset(offsetX);
            scrollViewer.ScrollToVerticalOffset(offsetY);
        }

0 个答案:

没有答案