winforms 使用单独的类操作窗体中的对象

slsn1g29  于 2022-11-17  发布在  其他
关注(0)|答案(1)|浏览(120)

我是C#的新手,我想在我的项目中应用低耦合。我有两个类,其中一个是窗体,另一个是常规类。我可以很容易地在两种窗体(我的另一个窗体)中使用示例,但如果我像我所说的那样将窗体和常规类连接起来,似乎就不能工作了。它显示(对象引用没有设置为对象的示例)。我该如何解决这个问题?
我的重要代码形式为:

namespace MMCM_Library
{
    public partial class MMCMLibrary_home : Form
    {
        public static MMCMLibrary_home instance;

        //DCR1 Labels
        public Label lbl1_1, lbl1_2, lbl1_3, lbl1_4;

        //DCR1 Labels
        public Label lbl2_1, lbl2_2, lbl2_3, lbl2_4;

        //DCR1 Labels
        public Label lbl3_1, lbl3_2, lbl3_3, lbl3_4;

        //DCR1 Labels
        public Label lbl4_1, lbl4_2, lbl4_3, lbl4_4;

        ReadandWrite read = new ReadandWrite();
        TimeFrame_Colors TimeFrame = new TimeFrame_Colors();


        public MMCMLibrary_home()
        {
            InitializeComponent();
            instance = this;

            TimeFrame.Colors();
  
            //DCR1
            lbl1_1 = lblDCR1_9;
            lbl1_2 = lblDCR1_11;
            lbl1_3 = lblDCR1_1;
            lbl1_4 = lblDCR1_3;

            //DCR2
            lbl2_1 = lblDCR2_9;
            lbl2_2 = lblDCR2_11;
            lbl2_3 = lblDCR2_1;
            lbl2_4 = lblDCR2_3;

            //DCR3
            lbl3_1 = lblDCR3_9;
            lbl3_2 = lblDCR3_11;
            lbl3_3 = lblDCR3_1;
            lbl3_4 = lblDCR3_3;

            //DCR4
            lbl4_1 = lblDCR4_9;
            lbl4_2 = lblDCR4_11;
            lbl4_3 = lblDCR4_1;
            lbl4_4 = lblDCR4_3;

        }

我的班级:

  • 我用了试错法 *
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace MMCM_Library
{
    internal class TimeFrame_Colors : Form
    {
        ReadandWrite read = new ReadandWrite();
        
        public static TimeFrame_Colors instance;
        public void Colors()
        {
            instance = this;
            //COLOR OF DCR1_9
            if (read.readExcel(1, 1) == "0")
            {
                MMCMLibrary_home.instance.lbl1_1.BackColor = System.Drawing.Color.Red;

            }
            else if (read.readExcel(2, 2) == "1")
            {
                MMCMLibrary_home.instance.lbl1_1.BackColor = System.Drawing.Color.Red;
            }
dfuffjeb

dfuffjeb1#

public MMCMLibrary_home()
{
    InitializeComponent();
    instance = this;
    //Because lbl1_1 is null value
    //You need to call TimeFrame.Color() after asign lbl1_1~lbl4_4

    //TimeFrame.Colors();

    //DCR1
    lbl1_1 = lblDCR1_9;
    lbl1_2 = lblDCR1_11;
    lbl1_3 = lblDCR1_1;
    lbl1_4 = lblDCR1_3;

    //DCR2
    lbl2_1 = lblDCR2_9;
    lbl2_2 = lblDCR2_11;
    lbl2_3 = lblDCR2_1;
    lbl2_4 = lblDCR2_3;

    //DCR3
    lbl3_1 = lblDCR3_9;
    lbl3_2 = lblDCR3_11;
    lbl3_3 = lblDCR3_1;
    lbl3_4 = lblDCR3_3;

    //DCR4
    lbl4_1 = lblDCR4_9;
    lbl4_2 = lblDCR4_11;
    lbl4_3 = lblDCR4_1;
    lbl4_4 = lblDCR4_3;

    TimeFrame.Colors();

}

相关问题