CTreeCtrl保存在运行时添加的项目

时间:2017-11-14 06:47:39

标签: c++ serialization mfc treeview

我需要动态添加CTreeCtrl项目

Serialize确实应该这样做吗? 只需要转换如果是变量类型

如果没有怎么办?

序列化功能

if (ar.IsStoring())
{
    ar >> m_tree1;
}
else
{
    ar << m_tree1;
}

1 个答案:

答案 0 :(得分:2)

序列化树并不复杂。这里有一个带有一些伪代码但没有错误的函数。

您唯一需要做的就是序列化节点数据......

不会针对编译器检查此代码,但应显示如何实现此目的。代码记录在案。

...
SerializeTree(m_tree.GetRootItem(), ar);
...

void SerializeTree(CTreeCtrl &tree, HTREEITEM hItem, CArchive &ar)
{
  if ar.IsStoring())
  {
    // Count items on this level
    DWORD dwCnt = 0;
    for (HTREEITEM hNext = hItem; hNext; hNext = tree.GetNextItem(hNext,TVGN_NEXT)
      ++dwCnt;
    // output data on this level
    ar << dwCnt;
    for (HTREEITEM hNext = hItem; hNext; hNext = tree.GetNextItem(hNext,TVGN_NEXT)
    {
      // Output data of this node
      OutputDataOfNode(tree,hNext,ar);
      // Stream children of this node
      SerializeTree(tree,tree.GetChildItem(hNext),ar);
    }
  }
  else
  {
    // Get number of nodes on this level
    DWORD dwCnt;
    ar >> dwCnt;
    while (dwCnt--)        
    {
      // Insert a new node
      HTREEITEM hNext = tree.InsertItem(_T(""),hItem ? hItem : TVI_ROOT, TVI_LAST);
      // Read data of node into the new node hNext
      ReadDataOfNode(tree,hNext,ar);
      // Now read all children
      SerializeTree(tree,hNext,ar);
    }
  }
}