我通常也不关注这里的链接,但 CodeProject 是一个相当可靠的来源 imo,所以我看了一下。
编辑:我对你想要什么感到困惑。以下是你似乎真正想要的:
问题在于从另一个表单或其中的一部分引用表单或其中的一部分。这是处理库的进一步问题,添加示例应用程序的命名空间或依赖项等确实不应该搞砸。
所以你想要的是松散耦合。
这是一个使用库对象中的引用并注册方法来填充引用的解决方案。如果您不注册任何内容,该库将正常工作。
此解决方案可以更改和扩展,但我将把它留给注册两个对象:一个是控件,例如 TextBox;另一个是组件,例如一个 ToolStripItem。如果您只想引用 ToolStripItem,您可以省略对 Control 和 RegisterCtl 方法的引用。
在这种情况下,您可以也应该用“Component”代替“ToolStripItem”以使事情变得更加紧凑!
首先,您将转到操作的最终消费者PlotterGraphSelectCurvesForm。在这里添加这两个代码块:
public partial class PlotterGraphSelectCurvesForm : Form
{
private int selectetGraphIndex = -1;
private PlotterGraphPaneEx gpane = null;
// block one: a Control reference (if you like!):
Control myTextCtl;
public void RegisterCtl(Control ctl) { if (ctl != null) myTextCtl = ctl; }
// block one: a Component reference:
Component myTextComp;
public void RegisterComp(Component comp) { if (comp != null) myTextComp = comp; }
//..
接下来你编写你想要发生的事情,可能是这样的:
void tb_GraphName_TextChanged(object sender, EventArgs e)
{
if (selectetGraphIndex >= 0 && selectetGraphIndex < gpane.Sources.Count)
{
DataSource src = gpane.Sources[selectetGraphIndex];
String Text = tb_GraphName.Text;
// all controls have a Text:
if (myTextCtl != null) myTextCtl.Text = Text;
// here you need to know the type:
if (myTextComp != null) ((ToolStripItem) myTextComp).Text = Text;
//..
}
理论上,您现在需要做的就是在 Mainform 中注册 TextBox 和/或 ToolStripItem。但是,有一个复杂的问题:PlotterGraphSelectCurvesForm 不是从 Mainform 调用的!相反,它是从 UserObject PlotterGraphPaneEx 调用的,而 UserObject PlotterGraphPaneEx 又位于 MainForm 中。本着不通过创建依赖项来搞乱库的精神,您只需向此 UO 添加完全相同的引用和注册方法:
public partial class PlotterDisplayEx : UserControl
{
#region MEMBERS
Control myTextCtl;
public void RegisterCtl(Control ctl) { if (ctl != null) myTextCtl = ctl; }
Component myTextComp;
public void RegisterComp(Component comp) { if (comp != null) myTextComp = comp; }
//..
现在您可以在 MainForm 中实际注册东西了..:
public MainForm()
{
InitializeComponent();
display.RegisterCtl(aDemoTextBox);
display.RegisterComp(toolstriplabel1);
//..
..在 UO 中:
private void selectGraphsToolStripMenuItem_Click(object sender, EventArgs e)
{
if (GraphPropertiesForm == null)
{
GraphPropertiesForm = new PlotterGraphSelectCurvesForm();
GraphPropertiesForm.RegisterCtl(myTextCtl);
GraphPropertiesForm.RegisterComp(myTextComp);
}
//..
现在,当您打开 Properties 表单并更改 LabelText 时,您可以看到 Graphs 中的文本以及 Menu 和 TextBox 中的文本都发生了变化..