初步学习了WTL,用它做一个小东西。要用到树形控件来实现目录功能,后来又想到结合XML,将XML数据与树控件结合起来,便查资料干了起来O(∩_∩)O~
这两个东东其实都没用过,所以先从树控件入手,通过MSDN和其他百度到的资料,算是掌握了它的使用。WTL里的CTreeViewCtrl类和MFC的类差不多,它的使用会另外介绍。XML的使用网上也有很多资料,只有掌握其基本用法,接下来就方便了,可以通过源代码查看各函数的用法。下面记录下两者的结合使用。
简单说来就是根据XML内容来设置TreeViewCtrl的内容,并为树控件的每项设定一个ID值,可以根据ID值反过来在XML查找需要的数据内容。
下面是我的XML文件(没有任何代表意义):
自己定义TreView类(便于功能扩展):
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
class CMyTreeViewCtrl: public CWindowImpl{ public: BEGIN_MSG_MAP(CMyTreeViewCtrl) DEFAULT_REFLECTION_HANDLER() END_MSG_MAP() };
载入XML,遍历XML内容,将各节点显示到tree控件上:
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
![](https://images.cnblogs.com/OutliningIndicators/ExpandedBlockStart.gif)
void CMainFrame::RecursiveTravel(TiXmlElement *note, HTREEITEM hTreeItem) { int id; HTREEITEM hitem; TiXmlAttribute *name; TiXmlAttribute *IDAttribute; TiXmlElement *note_next = note->FirstChildElement(); while( note_next!= NULL ) { IDAttribute = note_next->FirstAttribute(); name = IDAttribute->Next(); hitem = m_treeCtrl.InsertItem ( name->Value(), hTreeItem, TVI_LAST ); id = atoi( IDAttribute->Value() ); m_treeCtrl.SetItemData ( hitem, id ); RecursiveTravel( note_next, hitem ); note_next = note_next->NextSiblingElement(); } } void CMainFrame::LoadList() { TiXmlDocument *doc = new TiXmlDocument(m_strListXml); doc->LoadFile(); RecursiveTravel( doc->RootElement(), TVI_ROOT ); doc->SaveFile(); }
通过递归实现树的遍历,效率可能不高,不过比较方便,容易理解,呵呵。
下面介绍根据选中tree控件的选中,查询XML中的对应项。首先要响应选中消息,这里是响应TVN_SELCHANGED消息,即选项变化时响应事件。因为上面用了ID作为tree控件Item的data值,所以这里通过GetItemData()可取得ID值。通过ID属性查询XML中对应选项的代码为:
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
![](https://images.cnblogs.com/OutliningIndicators/ExpandedBlockStart.gif)
1 /******************************************* 2 note ---要查询的XML的根项 3 id ---ID号 4 destNote---输出结果 5 *******************************************/ 6 bool CMainFrame::FindNoteByID(TiXmlElement *note, int id, TiXmlElement* &destNote) 7 { 8 TiXmlAttribute *IDAttribute; 9 TiXmlElement *note_next = note->FirstChildElement(); 10 11 while( note_next!= NULL ) 12 { 13 IDAttribute = note_next->FirstAttribute(); 14 if( atoi( IDAttribute->Value() ) == id ) 15 { 16 destNote = note_next; 17 return true; 18 } 19 20 if( FindNoteByID( note_next, id, destNote ) ) 21 { 22 return true; 23 } 24 note_next = note_next->NextSiblingElement(); 25 } 26 27 return false; 28 }
这样就实现了tree控件对XML的绑定,根据自己想法,这样可以通过XML来记录tree控件的数据,可对其添加删除。而且在XML中还可以记录对应tree项的其他数据内容。