简体   繁体   中英

C#/WPF - Get ScrollViewer scroll position?

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.

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?

(Hint: myScrollViewer.VerticalOffset and ContentVerticalOffset are both 0; myScrollViewer.ScrollInfo just plain doesn't exist.)

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 scroll as intended. Goes right exactly where I want it to. But, myScrollViewer.VerticalOffset is set at 0.

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

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

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

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!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM