我正在 Windows 窗体中转换 WPF 客户端,但在尝试复制 TreeView 控件结构时遇到了一些问题。
在第一个项目中,我有一个自定义工厂,它从基本上是 XML 的输入字符串开始构建结构。返回类型是一个集合。自定义树节点:
public class TreeViewNode
{
public TreeViewNode() { }
public DocumentKey DocKey { get; set; }
public string Text { get; set; }
public IList<TreeViewNode> Children { get; set; }
}
工厂:
public class TreeViewFactory
{
public IList<TreeViewNode> GetSctructure(DocumentKey docKey, string structure, bool loadAllParents)
{
XDocument xmlDocstructure = CommonXmlValueParser.GetXDocument(structure);
var parentsNodes = (from item in xmlDocstructure.Descendants("structure_item")
where (CommonXmlValueParser.GetAttribute(item, "level") == "1")
select new TreeViewNode
{
Text = GetNodeText(item),
DocKey = new DocumentKey()
{
Bank = docKey.Bank,
Ud = int.Parse(CommonXmlValueParser.GetElement(item.Element("ud"))),
Master = int.Parse(CommonXmlValueParser.GetElement(item.Element("master"))),
NVig = int.Parse(CommonXmlValueParser.GetElement(item.Element("nvig"))),
Subjects = docKey.Subjects
},
Children = GetChildrenNodes(item, 2, docKey.Bank)
}).ToList();
return parentsNodes;
}
private IList<TreeViewNode> GetChildrenNodes(XElement element, int level, int dataBank)
{
var childrenNodes = (from item in element.Descendants("structure_item")
where (CommonXmlValueParser.GetAttribute(item, "level") == level.ToString())
select new TreeViewNode
{
Text = GetNodeText(item),
DocKey = new DocumentKey()
{
Bank = dataBank,
Ud = int.Parse(CommonXmlValueParser.GetElement(item.Element("ud"))),
Master = int.Parse(CommonXmlValueParser.GetElement(item.Element("master"))),
NVig = int.Parse(CommonXmlValueParser.GetElement(item.Element("nvig"))),
},
Children = GetChildrenNodes(item, level + 1, dataBank)
}).ToList();
return childrenNodes;
}
}
捆绑:
void CreateTree(object tree, EventArgs e)
{
//...
TreeViewFactory treeFactory = new TreeViewFactory();
var documentStructure = treeFactory.Structure(document.DocumentKey, document.XmlStructure, true);
this.tabMainControl.document.SetTreeViewStructureNodes(documentStructure);
}
public void SetTreeViewStructureNodes(IList<TreeViewNode> nodes)
{
this.treeView.ItemsSource = nodes;
}
更新:
我使 TreeViewNode 从 TreeNode 派生并更改了 SetTreeViewStructureNodes 方法:
private TreeView SetTreeViewStructureNodes(IList<TreeViewNode> nodes)
{
TreeView treeView = new TreeView();
treeView.Nodes.AddRange(nodes.ToArray());
return treeView;
}
仍然没有达到我的目标,因为它仍然没有渲染......
据我所知,在 Windows 窗体中,不可能关联某种类型的数据源(实现 IEnumerable)。除了使用 3rd 方组件,我该如何解决我的问题。我在 WinForms 上的经验很短,当我学会管理更好的 WPF 时,他们决定改变它:(
感谢您的所有帮助,问候。
更新2:填充treeView的WinForms用户控件:
TreeView treeView = (TreeView)documentViewControl.Controls["treeViewStructure"];
TreeViewFactory treeFactory = new TreeViewFactory();
var documentStructure = treeFactory.GetStructure(document.DocumentKey, document.XmlStructure, true);
treeView = this.SetTreeViewStructureNodes(documentStructure);
基本上我正在从 UC 转到另一个。它们都是 2 个 Tabs 的一部分,是 TabControl 的子项。