在工作中碰到了一個奇葩的問題,ScrollViewer的ScrollIntoView方法一直沒用。
上網找了各種方法,幾乎都是說用UpdateLayOut就可以解決了,但是我的怎么也不行。
后來找了官方的文檔,對應地址是:http://msdn.microsoft.com/zh-cn/library/system.windows.controls.listbox.scrollintoview%28v=VS.96%29.aspx
里面有這么一段話:
If the specified object is not visible, calling ScrollIntoView causes it to align at the top or bottom of the viewport. When the contents of the ItemsSource collection changes, particularly if many items are added to or removed from the collection, you may need to call UpdateLayout() prior to calling ScrollIntoView for the specified item to scroll into the viewport.
大致的意思就是:如果對象不可見,調用ScrollIntoView方法會讓對象在視區的頂部或者底部對齊。當ItemSource的內容發生變化時,尤其是里面的一些元素被添加或者移除時,你需要在調用ScrollIntoView 方法之前調用UpdateLayout()方法,這樣才能將對應的元素調入視區。
好吧,我的問題是第一種。。。幾個Tab頁面切換,ScrollViewer在第二個Tab,第一個Tab中的部分功能調用了對第二個Tab頁面的ScrollViewer調用了ScrollIntoView方法,結果切換回來的時候怎么都是在頂部的。。。
當然,最后的解決方案是:在切換到第二個Tab的時候,再調用一次ScrollIntoView,那樣就OK了。折磨了一天的Bug終於解決。。。
第一篇blog,希望能幫助到也為這個問題抓狂的程序員們