C#:如何从另一个自定义控件访问自定义控件的公共成员

时间:2011-04-18 11:54:19

标签: c# winforms custom-controls

我正在处理Windows应用程序表单。我有一个CustomControl(比如MasterControl),我把它放在一个分割面板上,现在我的MasterControl被分成三部分说:

  • Pannel1
  • Pannel2
  • Pannel3

现在我开发了三个自定义控件,并在每个面板中放置一个,例如

  • Pannel1有CustomControl1
  • Pannel2有CustomControl2
  • Pannel3有CustomControl3

现在CustomControl3中的某处我需要访问CustomControl1的公共成员。我为此编写了以下代码:

((MasterControl)this.Parent)._oCustomControl1.PublicMember = this.PublicMember;

上面的代码在我的情况下不起作用。当这行代码在调试模式下执行时,会出现一个消息框,并指出“没有可用于当前位置的代码”

3 个答案:

答案 0 :(得分:3)

答案 1 :(得分:2)

如果您的主控件中有一个拆分面板,您应该向上两级找到您的主控件:

((MasterControl)this.Parent.Parent)._oCustomControl1.PublicMember = this.PublicMember;

答案 2 :(得分:0)

我自己找到了答案。我在这里假设,因为它可能会帮助其他人。 确切的代码是:

((MasterControl)this.Parent.Parent.Parent)._oCustomControl1.PublicMember = this.PublicMember;

基本上我的coustomcontrol3位于拆分容器面板内,所以当我写道: this.Parent然后它指向它居住的Panel,如果我写的话 this.Parent.Parent然后它指向上面面板所在的spliter容器,如果我写的话 this.Parent.Parent.Parent然后它指向此拆分容器所在的控件

我从“Farzin Zaker”的回答中得到了这个想法,所以感谢他的贡献

相关问题