在 WinForms 中从外部访问时用户控件 属性 不可见

User control property not visible when accessed from outside in WinForms

情况

目标

我尝试的是将 resultsControl 中的 dataGridView1 作为 属性 公开,并在 startControl 中访问它的 DataSource 但出于某种原因在 Form1startControl.

中我都看不到暴露的 属性

代码

public partial class resultsControl : UserControl
{
    public resultsControl()
    {
        InitializeComponent();
    }

    [PropertyTab("Data"), Description("Test"), Category("Misc"), Browsable(true)]
    public DataGridView dgvParameter
    {
        get
        {
            return this.dataGridView1;
        }
        set
        {
            this.dataGridView1 = value;
        }
    }
}

我似乎无法使用 resultsControl.dgvParameter 访问我的 dataGridView1 - 我做错了什么?

编辑

如前所述,我需要使用 resultsControl 的一个实例。我已经在我的 Form1 中创建了一个 resultsControl 的实例 - 这意味着我只需要从我的 startControl 用户控件访问它,对吗?

我的第一个猜测是在 Form1 中公开另一个 属性 还是有其他方法可以从我的(父)表单访问它?

代码

public partial class homeForm : Form
    {
        public homeForm()
        {
            InitializeComponent();
        }

        private void btnDashStart_Click(object sender, EventArgs e)
        {
            startControl control = new startControl();
            ShowControl(control);
        }

        private void btnDashResults_Click(object sender, EventArgs e)
        {
            resultsControl control = new resultsControl();

            ShowControl(control);
        }

        public void ShowControl (Control control)
        {
            containerPanel.Controls.Clear();

            control.Dock = DockStyle.Fill;
            control.BringToFront();
            control.Focus();
            containerPanel.Controls.Add(control); 
        }
}

您需要使用 resultsControl 实例 ,因为您的 dgvParameter 不是 static 属性。

进入设计器视图并单击您的控件。在"Properties"window中查看'Name'属性。那是您的实例的名称,例如resultsControl1。现在您可以在代码中使用 resultsControl1.dgvParameter

顺便说一下,您应该遵守命名约定,即属性和 类 应该使用 UpperCamelCase 命名。