简体   繁体   中英

Adding text to a RichTextBox in the constructor

I'm creating a special kind of textbox, by inheriting from RichTextBox. I would like to be able to set the initial text in the box, which I thought I could do in the constructor as follows:

class SpecialTextBox : RichTextBox
{
    public SpecialTextBox()
    {
        BackColor = System.Drawing.Color.ForestGreen;
        AppendText("Initial Text...");
        Text += "and some more initial text.";
    }
}

The constructor in the above code sets the background colour, but the initial text does not appear. My question is, why doesn't the text appear, and how can I achieve this? I might want the initial text to be configurable (perhaps passed in to the constructor).

I can successfully add text later, by calling

specialTextBox1.AppendText("This text will appear.")

Why doesn't the constructor text appear?

Windows is overwriting the text inside the FlowDocument when it loads the XAML for it. This happens after the constructor for the RichTextBox is called.

Try adding the text a bit later, for instance in the Loaded event:

public class SpecialTextBox : RichTextBox
{
    public SpecialTextBox()
    {
        Background = new SolidColorBrush(System.Windows.Media.Color.FromArgb(
            System.Drawing.Color.ForestGreen.A,
            System.Drawing.Color.ForestGreen.R,
            System.Drawing.Color.ForestGreen.G,
            System.Drawing.Color.ForestGreen.B));

        this.Loaded += new RoutedEventHandler(SpecialTextBox_Loaded);
    }

    void SpecialTextBox_Loaded(object sender, RoutedEventArgs e)
    {
        AppendText("Initial Text...");
    }
}

Update: you might only want to do this if the XAML that got loaded has no initial text:

    void SpecialTextBox_Loaded(object sender, RoutedEventArgs e)
    {
        var range = new TextRange(Document.ContentStart, Document.ContentEnd);
        if (range.IsEmpty)
        {
            AppendText("Initial Text...");
        }
    }

Update

OK, WinForms. WinForms sets the initial text in the c# code generated by the designer. You should see something like this:

        this.richTextBox1 = new WinformsRichTextBox.SpecialTextBox();
        this.SuspendLayout();
        // 
        // richTextBox1
        // 
        this.richTextBox1.Location = new System.Drawing.Point(12, 2);
        this.richTextBox1.Name = "richTextBox1";
        this.richTextBox1.Size = new System.Drawing.Size(1233, 507);
        this.richTextBox1.TabIndex = 0;
        this.richTextBox1.Text = "";

That last line is what defeats your constructor. You can hack around this by overriding the Text method and rejecting the initial setting:

public class SpecialTextBox : RichTextBox
{
    bool suppressInitialSetText = true;

    public SpecialTextBox()
    {
        BackColor = System.Drawing.Color.ForestGreen;
        AppendText("Initial Text...");

        this.VisibleChanged += new EventHandler(SpecialTextBox_VisibleChanged);
    }

    void SpecialTextBox_VisibleChanged(object sender, EventArgs e)
    {
        // Just in case, once the control becomes visible disable the kludge.
        if (Visible)
            suppressInitialSetText = false;
    }

    public override string Text
    {
        get
        {
            return base.Text;
        }
        set
        {
            if (!suppressInitialSetText || !string.IsNullOrEmpty(value) || Parent != null)
                base.Text = value;
            suppressInitialSetText = false;
        }
    }
}

In this scheme the "Initial Text..." only appears if the "Text" line in the forms designer is empty. Otherwise the text in the forms designer overrides the text in the constructor.

Seems sort of fragile and kludgy though.

So "Initial Text..." does not appear, but "and some more initial text." does? At first glance, it would appear that you're clobbering the first string by assigning the second...except that you're using the += operator and not =.

I've never used the AppendText method, but I can offer some guesses:

  1. Maybe AppendText doesn't work if the Text property is blank? So the result of calling it here is nothing?
  2. Maybe AppendText changes the display, but not the Text property? So Text is still blank when you add the second string, which then updates the display to show Text?

Try commenting out the Text += ... line and see if it displays the first one. Also put a breakpoint just before and after AppendText to see what happens to Text.

In the constructor you can set the initial text as

base.Text = "Text what ever you want";

I added your class to a Windows Forms project and added it to a form in the Load event. It seems to work as expected. How are you added the SpecialTextBox to your form?

This is what my Load event looks like.

    private void Form1_Load(object sender, EventArgs e)
    {
        SpecialTextBox stb = new SpecialTextBox();
        this.Controls.Add(stb);
        stb.Visible = true;
    }

This is what the class looks like.

    class SpecialTextBox : System.Windows.Forms.RichTextBox
    {
        public SpecialTextBox()
        {
            BackColor = System.Drawing.Color.ForestGreen;
            AppendText("Initial Text...");
            Text += "and some more initial text.";
        }
    }

It's caused by the designer-generated code in the .designer.cs of your form containing your SpecialTextBox .

To customize that code, you can define a custom ControlDesigner and override InitializeNewComponent as followings:

internal class SpecialTextBoxDesigner
 : System.Windows.Forms.Design.ControlDesigner
{
    public override void InitializeNewComponent(
        System.Collections.IDictionary defaultValues)
    {
        base.InitializeNewComponent(defaultValues);
        this.Control.Text = "Initial Text...";
    }
}

Then apply that by DesignerAttribute to your SpecialTextBox :

[System.ComponentModel.Designer(typeof(SpecialTextBoxDesigner))]
public partial class SpecialTextBox : RichTextBox

You need to add a reference to System.Designer into your project beforehand.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM