【问题标题】:Public function not working properly公共功能无法正常工作
【发布时间】:2012-10-19 11:49:39
【问题描述】:

我有以下两段代码,请看一下,我指出了哪里出错了。 我删除了调用第二个窗口的函数,它们在这里没有意义。

第一,主窗体,这个窗体调用第二个窗体:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Runtime.InteropServices;

namespace STP_Design
{
    public partial class STP2Main : Form
    {
        public STP2Main()
        {
            InitializeComponent();
            tabControl1.SelectedTab = tabPageDeviceManager;
        }
        private void pictureBox1_Click(object sender, EventArgs e)
        {
            MenuForm MDIMF = new MenuForm();
            MDIMF.MdiParent = this;
            MDIMF.StartPosition = FormStartPosition.Manual;
            MDIMF.Location = new Point(3, 50);
            MDIMF.Show();
            tabControl1.Visible = false;
        }

        public void set()
        {
            tabControl1.Visible = true; // This statement executes, but does not result in anything I'd expect. The debugger tells me the visibility is false.
            tabControl1.BringToFront();
        }
   }
}

第二个表单,我关闭并更新第一个表单:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace STP_Design
{
    public partial class MenuForm : Form
    {
        public MenuForm()
        {
            InitializeComponent();

            this.BringToFront();
        }


        private void button1_Click(object sender, EventArgs e)
        {
            STP2Main stp = new STP2Main();
            stp.set();
            this.Close();
        }
    }
}

【问题讨论】:

  • 您看到的行为是什么?
  • “调用第二个窗口”代码可能非常重要。
  • 实际显示 STP2Main 的代码在哪里?
  • 我在打开第二个表单时使我的 tabcontrol 框不可见,如果我关闭表单并尝试使 tabcontrol 可见,它根本不会出现。我在应该设置可见性的行上设置了一个断点。它说它不可见(没错)但仍然不可见......
  • 我再添加一些代码,1 秒

标签: c# winforms function public


【解决方案1】:

您在主窗体的 版本上调用set 方法,而不是在您可能已经向用户显示的版本上。

您需要做的是从菜单窗体的MdiParent 属性中获取当前 主窗体,然后调用that 上的方法。

// In menu form
private void button1_Click(object sender, EventArgs e)
{
    var mainForm = this.MdiParent as STP2Main;
    if (mainForm != null)
        mainForm.set();
    this.Close();
}

【讨论】:

  • 好的,所以我应该更改“STP2Main stp = new STP2Main();”到“ public STP2Main MainForm { get; set; }”。当我这样做时,我在“MainForm.Set();”上得到一个空引用错误
  • @2pietjuh2 我已更改我的代码以匹配您发布的代码,希望这对您有用。
猜你喜欢
  • 2014-03-18
  • 2017-09-23
  • 2013-11-06
  • 2013-10-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多