簡體   English   中英

按下按鈕時如何更改文本框中的文本?

[英]How to change text in textbox when I press the button?

首先,我是 C# 的初學者,我想有一天成為一名游戲開發者。 所以我在這里,問你這個簡單的問題。 但不適合我。

問題是,我希望我的代碼在按下按鈕時更改文本。 想象一下,你正在玩我在這里嘗試制作的基於文本的冒險游戲,當你按下按鈕時,每次按下它都會改變文本。

但我的代碼沒有,這是我的代碼在此處輸入圖像描述

代碼沒有錯,但它沒有按我的預期工作。 它只會顯示最后一個,而不是從第一個到最后一個。

如果您能幫助我發展這方面的知識,我將不勝感激。

您可以循環遍歷arrayList

這是一個非常簡單的例子:

using System;
using System.Collections.Generic;
using System.Windows.Forms;

namespace TextLineByLine
{
    public partial class Form1 : Form
    {
        List<string> Messages = new List<string>();
        int currentLine = -1;

        public Form1()
        {
            InitializeComponent();

            // Add some messages
            Messages.Add("You open your eyes");
            Messages.Add("The bright blue sky is up there");
            Messages.Add("And some blood covers the ground");
            Messages.Add("You're not sure what happened...");
        }

        private void button1_Click(object sender, EventArgs e)
        {
            currentLine++; // increment the line index
            if (currentLine < Messages.Count)
            {
                Title.Text = Messages[currentLine];
            }
            else
            {
                Title.Text = "-= Nothing to display =-";
            }
        }
    }
}

如果我很好地理解了您的問題,您希望每次按下時都會更改文本。

例如,您可以使用 Integer 輕松完成。

public partial class MainWindow : Window 
{
    int dialogue = 0;
    public MainWindow() { InitializeComponent(); }
    private void btnAction_Clickl(object sender, RoutedEventArgs e) 
    {
        switch ( dialogue ) 
        {
            case 0:
                Title.Text = "Some text";
                dialogue++;
                break;
            case 1:
                Title.Text = "Another text";
                dialogue++;
                break;
            default: //just in case you want to reset the text
                Title.Text = "First text";
                dialogue = 0;
                break;
         }
    }
}

如果您想將其設置為自動,例如只需單擊一次,然后文本每 x 秒更改一次,您可以使用:

public partial class MainWindow : Window 
{
    public MainWindow() { InitializeComponent(); }
    private void btnAction_Clickl(object sender, RoutedEventArgs e) 
    {
        Dialogue();
    }
    
    private async void Dialogue()
    {
        Title.Text = "Some text";
        await Task.Delay(2000); // Where 2000 means 2 seconds in milliseconds
        Title.Text = "More text"; // And so on...
    }
}

祝你今天過得愉快。

好吧,您可以像這樣為您的句子創建一個字符串數組並執行以下操作。

int counter = 0;

private void btnAction_Click(object sender, RoutedEventArgs e)
{
    string[] messages = new string[4]
    messages[0] = "Your first message";
    messages[1] = "Your second message";
    messages[2] = "Your third message";
    messages[3] = "Your fourth message";
    
    title.Text = messages[0];
    counter++;
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM