Dot-Net
保持樹視圖的滾動位置
如何在 .NET 應用程序中保持樹視圖控制項的滾動位置?例如,我有一個樹形視圖控制項,並經歷了一個向其添加各種節點的過程,並將它們固定在底部。在此過程中,我可以滾動瀏覽樹視圖並查看不同的節點。問題是當過程完成時,樹視圖滾動到最底部。
看來呼叫 treenode.Expand() 是讓我偏離軌道的原因。當父節點展開時,它會獲得焦點。
有沒有解決的辦法?如果我在程序執行時查看特定節點,我不希望它在程序完成後跳到我身上。
我想我想通了:
- 獲取樹視圖頂部的節點。
- 展開父節點。
- 使之前位於頂部的節點可見。
If treeNodeParent.IsExpanded = False Then Dim currentNode As TreeNode = TreeViewHosts.GetNodeAt(0, 0) treeNodeParent.Expand() currentNode.EnsureVisible() End If這是更好的方法嗎?
我不是 VB 人,但在 C# 中我是這樣做的:
一些 Win32 原生函式:
[DllImport("user32.dll", CharSet = CharSet.Unicode)] public static extern int GetScrollPos(IntPtr hWnd, int nBar); [DllImport("user32.dll", CharSet = CharSet.Unicode)] public static extern int SetScrollPos(IntPtr hWnd, int nBar, int nPos, bool bRedraw); private const int SB_HORZ = 0x0; private const int SB_VERT = 0x1;返回目前滾動位置的點的方法:
private Point GetTreeViewScrollPos(TreeView treeView) { return new Point( GetScrollPos(treeView.Handle, SB_HORZ), GetScrollPos(treeView.Handle, SB_VERT)); }設置滾動位置的方法:
private void SetTreeViewScrollPos(TreeView treeView, Point scrollPosition) { SetScrollPos(treeView.Handle, SB_HORZ, scrollPosition.X, true); SetScrollPos(treeView.Handle, SB_VERT, scrollPosition.Y, true); }然後,當您更新樹時,請執行以下操作:
BeginUpdate(); Point ScrollPos = GetTreeViewScrollPos(treeMain); // write your update code here SetTreeViewScrollPos(treeMain, ScrollPos); EndUpdate();