首页 > 解决方案 > 如何将 BackColore 颜色存储为一种方法,并在 C# 中以不同的方法使用它

问题描述

我构建了一个为面板保存 BackColor 的方法,如果我在新方法中调用该方法,颜色将不会显示

这是我的代码'''''''''''''''''''''''''''''''''''''''''' ''''''

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Drawing;

namespace WindowsFormsApplication24
{
    class theme
    {
        public static void dark()
        {
            Form1 f = new Form1();
           Color c= f.panel1.BackColor = Color.Black;

        }

    }
}

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

namespace WindowsFormsApplication24
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
           theme.dark();

        }
    }
}

''''''''''''''''''''''''''''''''''''''''''''' ''''''''''''''''


标签: c#

解决方案


new Form1()您实例化的是该类的一个实例,Form1但许多Form1实例可以同时存在。你想传递Form1你试图改变的实例。尝试:

private void Form1_Load(object sender, EventArgs e)
{
  theme.dark(this);
}

和:

public static void dark(Form1 f)
{
  f.panel1.BackColor = Color.Black;
}

推荐阅读