【问题标题】:Textbox wont update文本框不会更新
【发布时间】:2014-12-13 14:08:30
【问题描述】:

所以我正在用 c# 制作一个基本的 yahtzee 程序,并且我正在尝试制作一个实际的 gui 而不仅仅是使用控制台。但是我的文本框有问题。当我掷骰子时,我希望文本框显示掷出的数字。现在它什么也没显示。我使用两个类,一个用于实际程序,一个用于处理 gui。这是 yahtzee 类:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace Yahtzee
{
    class YahtzeeScorer {
        Random rndm = new Random();
        Form1 gui = new Form1();
        String dice1, dice2, dice3, dice4, dice5;

       public void rollDice()
        {
            String a = Console.ReadLine();
            this.dice1 = rndm.Next(1, 7).ToString();
            this.gui.tbDice_SetText(this.dice1);
        }

        static void Main(String[] args) {
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            YahtzeeScorer ys = new YahtzeeScorer();
            Application.Run(ys.gui);
            ys.rollDice();
            Console.WriteLine("The result was: " + ys.dice1 );
            Console.Read();
        }

    }
}

这是 gui 类 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 Yahtzee
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        public void tbDice_SetText(String s)
        {
            //this.ActiveControl = tbDice;
            Console.WriteLine("SetText");
            tbDice.Text = s;
        }

        public void textBox1_TextChanged(object sender, EventArgs e)
        {

        }



    }
}

tbDice 是文本框组件的名称。有什么想法吗?

【问题讨论】:

    标签: winforms user-interface textbox


    【解决方案1】:

    检查行:

    Application.Run(ys.gui);
    ys.rollDice();
    

    在应用程序退出之前不会调用rollDice(),因为运行Main() 的线程将阻塞Application.Run(),直到它退出。

    请尝试在按钮事件处理程序中调用ys.rollDice()

    更新

    通过将两个方面都放入 YahtzeeScorer 中,您可以混合您的游戏逻辑和演示逻辑。我建议您将游戏逻辑移动到一个单独的类中,如下所示:

    public class YahtzeeGame
    {
         public string rollDice()
         {
            return rndm.Next(1, 7).ToString();
         }    
    }
    
    
    public partial class Form1 : Form
    {
        YahtzeeGame game = new YahtzeeGame();
    
        public Form1()
        {
            InitializeComponent();
        }
    
        // You need to create a new Button on your form called btnRoll and 
        // add this as its click handler:
        public void btnRoll_Clicked(object sender, EventArgs e)
        {
            tbDice.Text = game.rollDice();
        }
    }
    

    【讨论】:

    • 所以我想我无法在 form1 中创建 YahtzeeScorer 的实例,我可以从 yahtzeescorer 调用按钮按下操作吗?我可以在 YS 中决定 form1 中的按钮应该做什么吗?希望举个例子
    猜你喜欢
    • 2020-06-13
    • 2011-04-27
    • 1970-01-01
    • 2023-03-16
    • 1970-01-01
    • 2015-05-16
    • 2017-03-18
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多