C#/WPF - 获取 ScrollViewer 滚动位置?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13151603/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-10 01:46:07  来源:igfitidea点击:

C#/WPF - Get ScrollViewer scroll position?

c#wpf

提问by DigitalMan

Okay, so, everyone knows how to set the scroll position of a ScrollViewer. Entire essays and blog entries have been written about ScrollViewer.ScrollToVerticalOffset(), and there are a good few hundred questions with answers about it here.

好了,大家都知道如何设置ScrollViewer的滚动位置了。已经写了整篇文章和博客条目ScrollViewer.ScrollToVerticalOffset(),这里有数百个问题及其答案。

So, I enter:

所以,我输入:

myScrollViewer.ScrollToVerticalOffset(280);

... and it so kindly scrolls to that location.

...它非常友好地滚动到那个位置。

The question is, what property now contains 280, so I can retrieve it later?

问题是,现在什么属性包含 280,以便我以后可以检索它?

(Hint: myScrollViewer.VerticalOffsetand ContentVerticalOffsetare both 0; myScrollViewer.ScrollInfojust plain doesn't exist.)

(提示:myScrollViewer.VerticalOffsetContentVerticalOffset都是 0;myScrollViewer.ScrollInfo只是简单的不存在。)

EDIT: Apparently I need a more detailed demonstration.

编辑:显然我需要更详细的演示。

private void btnTest_Click(object sender, RoutedEventArgs e) {
  double scrollTarget = 280;
  MessageBox.Show("Target: " + scrollTarget.ToString());
  myScrollViewer.ScrollToVerticalOffset(scrollTarget);
  MessageBox.Show("Now: " + myScrollViewer.VerticalOffset);
}

I must reiterate that this does scrollas intended. Goes right exactly where I want it to. But, myScrollViewer.VerticalOffsetis set at 0.

我必须重申,这确实按预期滚动。正好在我想要的地方。但是,myScrollViewer.VerticalOffset设置为 0。

采纳答案by DigitalMan

The solution is to manually call myScrollViewer.UpdateLayout()after myScrollViewer.ScrollToVerticalOffset(). Then, myScrollViewer.VerticalOffsetwill have the expected value.

该解决方案是手动呼叫myScrollViewer.UpdateLayout()之后myScrollViewer.ScrollToVerticalOffset()。那么,myScrollViewer.VerticalOffset就会有期望值。

回答by Erti-Chris Eelmaa

Make sure your VerticalScrollBarVisibility="Visible" and VerticalScrollOffset will be 280 after LayoutUpdated event has been fired.

确保在触发 LayoutUpdated 事件后您的 VerticalScrollBarVisibility="Visible" 和 VerticalScrollOffset 将为 280。

回答by Mullaly

I think you are calling the myscrollViewer in the constructor of the window.

我认为您正在窗口的构造函数中调用 myscrollViewer 。

You can call them when you click a button or in loaded method for the window, so that the value gets updated in vertical offset values. That is, these value gets updated after you initialize your window!

您可以在单击按钮或窗口的加载方法时调用它们,以便在垂直偏移值中更新值。也就是说,这些值会在您初始化窗口后更新!