我有一个使用递归从 XML 生成控件的过程。系统很复杂。我已经尽可能小了。最后一个插件是可见的,其余的不可见。我怀疑GenerateControls()
是坏了。为什么不显示所有插件?
形式:
public partial class PdLoadingForm : Form
{
public PdLoadingForm()
{
InitializeComponent();
PhysDocDocument document = MockDocument();//Generate some mock data
GenerateControls(document.Nodes);//Generate controls using recursion.
}
private PhysDocDocument MockDocument()
{
PhysDocDocument document = new PhysDocDocument();
PhysDocNode outerNode = new PhysDocNode();
outerNode.Display = "outer Node";
//Generate 3 plugins. Each plugin generates a textbox. I only see 1 Textbox.
//I expect to see 3 textboxes.
for(int i = 0; i < 3; i++)
{
PhysDocNode innerNode = new PhysDocNode() { Display = "test" + i };
PhysDocNode innerNodeContent = new PhysDocNode() { Display = "IO" };
innerNodeContent.Plugins.Add(new Plugin());
innerNode.Nodes.Add(innerNodeContent);
outerNode.Nodes.Add(innerNode);
}
document.Nodes.Add(outerNode);
return document;
}
private void GenerateControls(List<PhysDocNode> children, CustomControl parent = null)
{
foreach (PhysDocNode node in children)
{
CustomControl parentControl = new CustomControl(node);
if (node.Nodes != null && node.Nodes.Count > 0)
GenerateControls(children: node.Nodes, parent: parentControl);
foreach (Plugin plugin in node.Plugins)
{
Control childControl = plugin.CreateUIControl();//Ask the plugin for a control
AddControl(childControl: childControl, parent: parentControl);
}
AddControl(childControl: parentControl, parent: parent);
}
}
private void AddControl(Control childControl, Control parent)
{
childControl.Dock = DockStyle.Top;
if(parent == null)//add to form
Controls.Add(childControl);
else//add to parent
parent.Controls.Add(childControl);
}
}
插入:
public class Plugin
{
[XmlAttribute]
public string type { get; set; }
public Control CreateUIControl()
{
TextBox testBox = new TextBox();
testBox.Text = "plugin";
return testBox;
}
}
自定义控件:
public class CustomControl: UserControl
{
public CustomControl(PhysDocNode nodeInfo)
{
InitializeComponent();
Label label = new Label();
label.Text = "Rtb..." + nodeInfo.Display;
label.Dock = DockStyle.Top;
contentPanel.Controls.Add(label);//just drop a panel on the user control in design view
}