C#更改usercontrol labeltext和背景颜色

时间:2015-03-13 20:15:31

标签: c#

我的问题很简单。我想点击Form1中会导致userControl1中的label1的面板,该面板将放置在form2上以更改为“文字”。

单击此面板也会更改所述userControl1的背景颜色。我收到错误"'TileInterFaceTest.Usercontrol1.label1' due to its protection level",这让我感到困惑。

即使单独运行换色代码,也无法达到预期效果。

要说清楚,在C#和编程方面,我是一个新手。我一直在使用Visual Basic,所以类,方法和对象的概念对我来说有点混乱。

以下是Form1的代码:

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 WindowsFormsApplication1
{
    public partial class Form1 : Form
    {


        public Form1()
        {
            InitializeComponent();
        }

        private void panel1_Click(object sender, EventArgs e)
        {
            Form2 form2 = new Form2();
            UserControl1 userControl1 = new UserControl1();
            form2.Show();
            userControl1.BackColor = System.Drawing.Color.Red;
            userControl1.LabelText = "Text";

        }

        private void panel1_Paint(object sender, PaintEventArgs e)
        {

        }

        private void Form1_Load(object sender, EventArgs e)
        {

        }
    }
}

UserControl1的代码:

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

namespace WindowsFormsApplication1
{
    public partial class UserControl1 : UserControl
    {
        public String LabelText
        {
            get
            {
                return label1.Text;
            }
            set
            {
                label1.Text = value;
            }
        }

        public UserControl1()
        {

            InitializeComponent();
        }

        private void UserControl1_Load(object sender, EventArgs e)
        {

        }
    }
}

1 个答案:

答案 0 :(得分:2)

label1private字段,这意味着您无法在课程UserControl1之外访问该字段。

您可以做的是在类UserControl1的定义中添加公共属性:

public String LabelText {
    get {
        return label1.Text;
    }
    set {
        label1.Text = value;
    }
}

然后使用此属性修改label1的文本值:

private void panel1_Click(object sender, EventArgs e)
{
    form2.Show();
    userControl1.BackColor = System.Drawing.Color.Red;
    userControl1.LabelText = "Text";
}