如何:向 TreeView 或 ListView 控件(Windows 窗体)添加自定义信息
可在 Windows 窗体 TreeView 控件中创建派生节点,或在 ListView 控件中创建派生项。 通过派生可添加任何所需字段,以及添加处理这些字段的自定义方法和构造函数。 此功能的用途之一是将 Customer 对象附加到每个树节点或列表项。 虽然此处的示例是关于 TreeView 控件的,但该方法同样适用于 ListView 控件。
派生树节点
创建一个从 TreeNode 类派生的新节点类,前者包含一个记录文件路径的自定义字段。
Class myTreeNode Inherits TreeNode Public FilePath As String Sub New(ByVal fp As String) MyBase.New() FilePath = fp Me.Text = fp.Substring(fp.LastIndexOf("\")) End Sub End Class
class myTreeNode : TreeNode { public string FilePath; public myTreeNode(string fp) { FilePath = fp; this.Text = fp.Substring(fp.LastIndexOf("\\")); } }
ref class myTreeNode : public TreeNode { public: System::String ^ FilePath; myTreeNode(System::String ^ fp) { FilePath = fp; this->Text = fp->Substring(fp->LastIndexOf("\\")); } };
使用派生的树节点
新的派生树节点可用作函数调用的参数。
在下例中,为文本文件位置设置的路径是 My Documents 文件夹。 这样做是出于一个假定,即假定大多数运行 Windows 操作系统的计算机都包含此目录。 这还使得具有最低系统访问级别的用户能够安全运行应用程序。
' You should replace the bold text file ' in the sample below with a text file of your own choosing. TreeView1.Nodes.Add(New myTreeNode (System.Environment.GetFolderPath _ (System.Environment.SpecialFolder.Personal) _ & "\ TextFile.txt ") )
// You should replace the bold text file // in the sample below with a text file of your own choosing. // Note the escape character used (@) when specifying the path. treeView1.Nodes.Add(new myTreeNode(System.Environment.GetFolderPath (System.Environment.SpecialFolder.Personal) + @"\TextFile.txt") );
// You should replace the bold text file // in the sample below with a text file of your own choosing. treeView1->Nodes->Add(new myTreeNode(String::Concat( System::Environment::GetFolderPath (System::Environment::SpecialFolder::Personal), "\\TextFile.txt")));
如果被传递了此树节点,且其类型为 TreeNode 类,则需强制转换为派生类。 强制转换是从一种对象类型到另一种对象类型的显式转换。 有关强制转换的详细信息,请参阅隐式转换和显式转换 (Visual Basic)、强制转换和类型转换 (Visual C#) 或强制转换运算符:() (Visual C++)。
Public Sub TreeView1_AfterSelect(ByVal sender As Object, ByVal e As System.Windows.Forms.TreeViewEventArgs) Handles TreeView1.AfterSelect Dim mynode As myTreeNode mynode = CType(e.node, myTreeNode) MessageBox.Show("Node selected is " & mynode.filepath) End Sub
protected void treeView1_AfterSelect (object sender, System.Windows.Forms.TreeViewEventArgs e) { myTreeNode myNode = (myTreeNode)e.Node; MessageBox.Show("Node selected is " + myNode.FilePath); }
private: System::Void treeView1_AfterSelect(System::Object ^ sender, System::Windows::Forms::TreeViewEventArgs ^ e) { myTreeNode ^ myNode = safe_cast<myTreeNode^>(e->Node); MessageBox::Show(String::Concat("Node selected is ", myNode->FilePath)); }