【发布时间】:2018-05-21 14:37:06
【问题描述】:
我现在感觉有点傻,因为我在任何地方都看到这是一个正常的程序,我就是找不到为什么我也不能这样做!
所以,情况如下,我有一个父表单和一个子表单。子表单具有公共属性。从父窗体,我想访问子窗体公共属性,但我不能。
我的代码如下:
父代码:
namespace myProgram.UserInterfaces
{
public partial class ProjectNew : Form
{
public ProjectNew()
{
InitializeComponent();
}
private void ButtonSelectCustomer_Click(object sender, EventArgs e)
{
using (Form f = new ProjectCustomerList())
{
this.SuspendLayout();
f.ShowDialog(this);
}
this.Show();
}
}
}
子代码:
namespace myProgram.UserInterfaces
{
public partial class ProjectCustomerList : Form
{
public EntCustomer _selectedCustomer = new EntCustomer();
public EntCustomer SelectedCustomer {
get
{
return _selectedCustomer;
}
}
public ProjectCustomerList()
{
InitializeComponent();
}
// --- other code ---
}
}
使用 (Form f = new ProjectCustomerList()) 之后,我想执行以下操作:var sCustomer = f.SelectedCustomer;,但是当我这样做时,Visual Studio 无法识别子窗体公共属性。
我做错了什么? :|
【问题讨论】:
-
这对于继承是正常的,因为在您的情况下 f 被处理为一个简单的表单。您可以将其类型转换为
ProjectCustomerList以访问该属性。is运算符也很有用。if(f is ProjectCustomerList) (f as ProjectCustomerList).SelectedCustomer或简单的using (ProjectCustomerList f = new ProjectCustomerList())... -
@FrankM,您应该将您的评论作为答案;这绝对是正确的。
-
另一个可以通过使用
var避免的错误... -
查看我的两个表单项目:stackoverflow.com/questions/34975508/…
标签: c# .net winforms properties parent-child