在C#窗体中,如何使用TextBox.Text作为另一个属性名称在文本框上显示文本

本文关键字:文本 属性 另一个 显示 窗体 TextBox 何使用 Text | 更新日期: 2023-09-27 18:01:12

在C#窗体中如何使用TextBoxText属性作为另一个名为TextBox的属性WritePublicText是否在多行文本框中显示文本?我正在编辑无法修改的C#游戏代码。我正试图在Visual Studio中准确地模拟游戏代码进行编辑,然后直接复制到游戏代码中。另外,我是C#的新手,所以试着把它静音。

此代码显示名为textBox1:的窗口窗体文本框上的文本

textBox1.Text = "Text to display'r'n"
                + "More Text'r'n"
                + "More Text2'r'n";

这是游戏中显示文本的代码。但我不知道如何让它在windows窗体文本框中显示文本。

textBox1.WritePublicText = "Text to display'r'n"
                + "More Text'r'n"
                + "More Text2'r'n";

其他想法:

也许可以在windows窗体上以另一种方式显示多行文字,这样我就可以做到这一点。

在C#窗体中,如何使用TextBox.Text作为另一个属性名称在文本框上显示文本

创建一个类并从Windows.Forms.TextBox.继承

像这个

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace WindowsFormsApplication
{
    public class CustomTextBox : TextBox
    {
        public String WritePublicText
        {
            get { return Text; }
            set { Text = value; }
        }
    }
}

这个工具现在和普通的TextBox完全一样,但现在它包含了一个名为"WritePublicText"的新方法,该方法设置并返回一个String。

重新构建您的应用程序,然后您将在工具箱中看到一个名为CustomTextBox的新工具,只需像其他组件一样拖放即可。

如果你的应用程序中已经有很多TextBox,你可以进入设计器文件,将"TextBox"更改为"CustomTextBox",然后重新生成。

编写TextBox的子类,该子类具有如下公共属性:

public String WritePublicText {
    get { return Text; }
    set { Text = value; }
}

并且在UI中使用该控件而不是TextBox

您可能还需要添加一个构造函数,以便在VisualStudio中使用表单设计器。查看项目中的Form1.Designer.cs文件(假设表单名为Form1;使用常识(,了解当前TextBox是如何创建的;这是您需要复制的构造函数。

作为一种替代方案,如果您允许使用方法而不是属性(此外,Write...动词听起来像的方法性的名称(,则可以实现扩展方法:

public static class TextBoxExtensions {
  public static void WritePublicText(this TextBox textBox, string value) {
    if (null == textBox)
      throw new ArgumentNullException("textBox");
    textBox.Text = value;
  }
}

// Extension method instead of property
textBox1.WritePublicText(
    "Text to display'r'n"
  + "More Text'r'n"
  + "More Text2'r'n");