我通过继承RichTextBox来创建一种特殊的文本框。我希望能够在框中设置初始文本,我认为我可以在构造函数中进行如下操作:
class SpecialTextBox : RichTextBox
{
public SpecialTextBox()
{
BackColor = System.Drawing.Color.ForestGreen;
AppendText("Initial Text...");
Text += "and some more initial text.";
}
}
上面的代码中的构造函数设置背景色,但不显示初始文本。我的问题是,为什么文本不出现?如何实现呢?我可能希望初始文本是可配置的(也许传递给构造函数)。
我可以稍后通过调用来成功添加文本
specialTextBox1.AppendText("This text will appear.")
为什么没有显示构造函数文本?
最佳答案
Windows为其加载XAML时将覆盖FlowDocument
中的文本。这是在RichTextBox
的构造函数被调用之后发生的。
稍后再尝试添加文本,例如在Loaded
事件中:
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...");
}
}
更新:您可能只想在加载的XAML没有初始文本的情况下执行此操作:
void SpecialTextBox_Loaded(object sender, RoutedEventArgs e)
{
var range = new TextRange(Document.ContentStart, Document.ContentEnd);
if (range.IsEmpty)
{
AppendText("Initial Text...");
}
}
更新资料
好的,WinForms。 WinForms在设计器生成的c#代码中设置初始文本。您应该会看到以下内容:
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 = "";
最后一行是击败您的构造函数的原因。您可以通过覆盖
Text
方法并拒绝初始设置来解决此问题: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;
}
}
}
在此方案中,仅当表单设计器中的“文本”行为空时,才会显示“初始文本...”。否则,表单设计器中的文本将覆盖构造函数中的文本。
虽然看起来有些脆弱和笨拙。
关于c# - 在构造函数中向RichTextBox添加文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25575331/