尝试使用静态方法更改标签

时间:2013-09-05 19:17:32

标签: c# label static-methods

我有两个表单Form1,其中包含类CharStats,Mainform具有类MainFormMainForm有一个与之关联的标签pcNameLabelCharStats包含一个按钮,该按钮可以在点击时更改pcNameLabel.Text。由于我在表单和类之间进行通信,因此我在SetInfo()内部设置了静态方法MainForm,该方法由StatTransfer()内的方法CharStats调用。整个过程几乎正常,但我不能从静态方法pcNameLabel.Text内部修改SetInfo(),因为静态非静态事物。那我该怎么做呢。

Mainform(我删除了一些处理变量的非相关数据)

public partial class MainForm : Form
    {
        int statHolder;
        int statAdjuster;
        string healthHolder;
        int finalHealth;
        int diceOut;
        int maxDice;
        int healingOnOff = 0;
        int pcOrEn = 0;
        int turnCount = 0;
        int diceType;
        int diceResult;
        public static int formInit = 0;
        public static string VariableLabel1;
        public static string Variable2;

        Random _r = new Random();


        public MainForm()
        {

            CharStats form = new CharStats();
            form.Show();

            InitializeComponent();
        }

        public static void SetInfo()
        {
            Variable2 = VariableLabel1;
            pcNameLabel.Text = Variable2;   
        }
    }

Form1(也删除变量处理数据)

public partial class CharStats : Form
    {
        string name = "";
        string health = "";
        string mana = "";
        string strength = "";
        string agility = "";
        string intelligence = "";


        public CharStats()
        {

            InitializeComponent();
        }

        void Fighter()
        {
        name = "Reginaldxxxxxxx";
        health = "200";
        mana = "50";
        strength = "16";
        agility = "12";
        intelligence = "6";
        }

        public void StatTransfer()
        {
            MainForm.VariableLabel1 = Name;
            MainForm.formInit = 1;
            MainForm.SetInfo();
        }

        void FighterButtonClick(object sender, EventArgs e)
        {
            Fighter();
            StatTransfer();
        }
    }

2 个答案:

答案 0 :(得分:0)

你的问题似乎是观察者模式的一个非常好的候选者。查看详细信息here

答案 1 :(得分:0)

试试这个

公共部分类MainForm:表单     { .....

    public MainForm()
    {


        InitializeComponent();

//=====>Be careful change initial order between InitializeComponent

        CharStats form = new CharStats();
        form.Show();
    }

    public void SetInfo()
    {
        Variable2 = VariableLabel1;
        pcNameLabel.Text = Variable2;   
    }
}

以次要形式

public partial class CharStats : Form
    {
.....
 public void StatTransfer()
        {
            MainForm parentForm = this.parentForm;
            parentForm.formInit = 1;
            parentForm.SetInfo();
        }
......
}