不,你不做50个重叠的面板.只需创建多个用户控件,例如,链接节点标记上的类型.您可以使用Activator来创建控件.创建1个树视图和1个面板:(PSEUDO CODE)
// create nodes:
TreeNode item = new TreeNode();
item.Tag = typeof(UserControl1);
TreeView.Nodes.Add( item );
// field currentControl
UserControl _currentControl;
// on selection:
TreeViewItem item = (TreeViewItem)sender;
if(_currentControl != null)
{
_currentControl.Controls.Remove(_currentControl);
_currentControl.Dispose();
}
// if no type is bound to the node, just leave the panel empty
if (item.Tag == null)
return;
_currentControl = (UserControl)Activator.Create((Type)item.Tag);
Panel1.Controls.Add(_currentControl);
Run Code Online (Sandbox Code Playgroud)
接下来的问题是,"我想在控件中调用save方法或RequestClose方法".为此,您应该在控件上实现一个接口,当您切换节点时,只需尝试将_currentusercontrol转换为IRequestClose接口并调用,例如,bool RequestClose(); 方法.
// on selection:
TreeViewItem item = (TreeViewItem)sender;
if(_currentControl != null)
{
// if the _currentControl supports the IRequestClose interface:
if(_currentControl is IRequestClose)
// cast the _currentControl to IRequestCode and call the RequestClose method.
if(!((IRequestClose)_currentControl).RequestClose())
// now the usercontrol decides whether the control is closed/disposed or not.
return;
_currentControl.Controls.Remove(_currentControl);
_currentControl.Dispose();
}
if (item.Tag == null)
return;
_currentControl = (UserControl)Activator.Create(item.Tag);
Panel1.Controls.Add(_currentControl);
Run Code Online (Sandbox Code Playgroud)
但这将是下一步.