所以你有一个显示 TreeNodes 的 TreeView 对象,其中每个 TreeNode 显示一个System.Xml.XmlNode。每个 TreeNode 的(子)节点对应于 XmlNode 的子节点。
您必须决定为 XmlNode 显示什么文本,但这是一个小问题。
class XmlTreeNode : System.Windows.Forms.TreeNode
{
public XmlTreeNode(System.Xml.XmlNode xmlNode) : base()
{
this.XmlNode = xmlNode;
string textToDisplay = xmlNode.ToDisplayText();
this.Text = textToDisplay;
foreach (var childXmlNode in xmlNode.xmlNodeList.Cast<XmlNode>())
{
XmlTreeNode childNode = new XmlTreeNode(childXmlNode);
this.Nodes.Add(childNode);
}
}
public XmlNode XmlNode {get; private set;}
}
当然,XmlNode 没有 ToDisplayText() 方法,所以让我们为此创建一个扩展函数。见extension methods demystified
static string ToDisplayText(this System.Xml.XmlNode xmlNode)
{
// TODO: what would you like to Display?
return xmlNode.Name;
}
当然您希望能够在 XmlTreeNodeView 中显示这些 XmlTreeNode:
class XmlTreeNodeView : System.Windows.Forms.TreeView
{
// default constructor: constructs empty XmlTreeNodeView:
public XmlTreeNodeView() : base() {}
// constructor fills the XmlTreeNodeView with the XmlNodes:
public XmlTreeNodeView(IEnumerable<XmlNode> xmlNodes) : base()
{
foreach (XmlNode xmlNode in xmlNodes)
{
this.Nodes.Add(new XmlTreeNode(xmlNode));
}
}
当然,如果单击其中一个节点,您希望得到通知
public class XmlTreeNodeEventArgs : EventArgs
{
public XmlNode XmlNode {get; set;}
}
在你的 XmlTreeView 类中:
public event EventHandler<XmlTreeNodeEventArgs> XmlNodeClicked;
protected virtual void OnXmlNodeClicked(XmlNode node)
{
return XmlNodeClicked?.Invoke(new XmlTreeNodeEventArgs() {XmlNode = node});
}
protected override void OnAfterSelect (System.Windows.Forms.TreeViewEventArgs e)
{
// get the XmlTreeNode that was clicked:
XmlTreeNode node = (XmlTreeNode)e.Node;
this.OnXmlNodeClicked(node);
}
好消息是,您必须做一些非常愚蠢的事情才能在 XmlTreeView 中获取除 XmlNodes 之外的其他内容。
如果您确实想防止添加与 XmlNode 不同的内容,则您的 XmlTreeView 不应继承自 TreeView,而应继承自 UserControl。 UserControl 应该在其中显示一个 TreeView。尽管此方法有效,但您必须复制要公开的所有 TreeView 功能。我不确定额外的工作是否超过了 XmlTreeView 仅包含 XmlTreeNodes 的额外安全成本。