2009-12-17 103 views
5

我有一個包裝樹視圖的scrollviewer。在滾動視圖中滾動到選定的Treeviewitem

我以編程方式填充樹視圖(未綁定),並將樹視圖展開到預定的treeviewitem。這一切都很好。

我的問題是,當樹展開時,我希望父視圖的scrollview滾動到我剛展開的treeviewitem。有任何想法嗎? - 請記住,樹形視圖可能在每次展開時都沒有相同的結構,因此排除只存儲當前滾動位置並重新設置爲...

回答

4

我遇到了同樣的問題, TreeView不滾動到選定的項目。我所做的是在將樹展開到選定的TreeViewItem後,我調用了Dispatcher Helper方法以允許UI更新,然後使用選定項上的TransformToAncestor來查找其在ScrollViewer中的位置。下面是代碼:

// Allow UI Rendering to Refresh 
    DispatcherHelper.WaitForPriority(); 

    // Scroll to selected Item 
    TreeViewItem tvi = myTreeView.SelectedItem as TreeViewItem; 
    Point offset = tvi.TransformToAncestor(myScroll).Transform(new Point(0, 0)); 
    myScroll.ScrollToVerticalOffset(offset.Y); 

這裏是DispatcherHelper代碼:

public class DispatcherHelper 
{ 
    private static readonly DispatcherOperationCallback exitFrameCallback = ExitFrame; 

    /// <summary> 
    /// Processes all UI messages currently in the message queue. 
    /// </summary> 
    public static void WaitForPriority() 
    { 
     // Create new nested message pump. 
     DispatcherFrame nestedFrame = new DispatcherFrame(); 

     // Dispatch a callback to the current message queue, when getting called, 
     // this callback will end the nested message loop. 
     // The priority of this callback should be lower than that of event message you want to process. 
     DispatcherOperation exitOperation = Dispatcher.CurrentDispatcher.BeginInvoke(
      DispatcherPriority.ApplicationIdle, exitFrameCallback, nestedFrame); 

     // pump the nested message loop, the nested message loop will immediately 
     // process the messages left inside the message queue. 
     Dispatcher.PushFrame(nestedFrame); 

     // If the "exitFrame" callback is not finished, abort it. 
     if (exitOperation.Status != DispatcherOperationStatus.Completed) 
     { 
      exitOperation.Abort(); 
     } 
    } 

    private static Object ExitFrame(Object state) 
    { 
     DispatcherFrame frame = state as DispatcherFrame; 

     // Exit the nested message loop. 
     frame.Continue = false; 
     return null; 
    } 
} 
+0

謝謝!這很好。應該知道這些物品需要首先「可視化」! – 2009-12-17 15:57:29

+0

看來,offet.Y是相對的,所以myScroll.ScrollToVerticalOffset(offset.Y);需要更改爲sv.ScrollToVerticalOffset(offset.Y + sv.VerticalOffset); – 2012-10-05 21:07:53

2

傑森的ScrollViewer中招是移動一個TreeViewItem到特定位置的好方法。

儘管存在一個問題:在MVVM中,您無法訪問視圖模型中的ScrollViewer。無論如何,這是一種方法。如果你有一個TreeViewItem,你可以走直到它的視覺樹,直到你到達嵌入ScrollViewer:

// Get the TreeView's ScrollViewer 
DependencyObject parent = VisualTreeHelper.GetParent(selectedTreeViewItem); 
while (parent != null && !(parent is ScrollViewer)) 
{ 
    parent = VisualTreeHelper.GetParent(parent); 
} 
相關問題