【问题标题】:Parent Form can't access Child Form Public Property - Winforms c#父窗体无法访问子窗体公共属性 - Winforms c#
【发布时间】: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


【解决方案1】:

这对于继承是正常的,因为在您的情况下 f 被处理为一个简单的表单。

您可以将其类型转换为ProjectCustomerList 以访问该属性。 is 运算符也很有用。

if (f is ProjectCustomerList)
{
    (f as ProjectCustomerList).SelectedCustomer =...;
}

或者干脆

using (ProjectCustomerList f = new ProjectCustomerList())
{
    f.SelectedCustomer =...;
}

在其他 cmets 中看到 var,也可以使用

using (var f = new ProjectCustomerList())
{
    f.SelectedCustomer =...;
}

【讨论】:

  • 我已经知道这个概念了,但是我没有把它和forms联系起来,它和其他人一样是一个Class,但是……我是个盲人! :) 既然你提到的是,它变得一清二楚!非常感谢@FrankM
猜你喜欢
  • 2022-11-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多