在构造函数中更改扩展的RichTextBox文本不起作用 [英] Changing an extended RichTextBox text in constructor doesn't work

查看:51
本文介绍了在构造函数中更改扩展的RichTextBox文本不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下课程:

public partial class RichTextBoxEx : RichTextBox
{
    public RichTextBoxEx()
    {
        InitializeComponent();
        Text = "Some Text";
    }
}

但是,当我将其放在窗体上并运行程序时, RichTextBox 为空.有什么问题,我该如何解决?

However, when I place it over a form and run the program, the RichTextBox is empty. What is the problem and how can I fix it?

我认为这里缺少一些基本知识,但是我无法弄清楚是什么,而且我也没有找到任何有关此的信息.

I assume there is something basic I'm missing here, but I cannot figure out what, and I did not manage to find any information about this.

推荐答案

通常尊重在控件的构造函数中设置的属性值.但是对于 Text 属性,情况有所不同.我已经在另一个 answer 中对此进行了描述.实际上,是控件设计器在 InitializeNewComponent 中设置了控件的 Text 属性.

The property values which you set in constructor of the control are usually respected. But for Text property, the case is a bit different. I've already described about it in another answer. In fact it's the control designer which sets Text property of the control in InitializeNewComponent.

作为一种选择,您可以创建并注册一个新的控件设计器,重写 InitializeNewComponent 并捕获 Text 属性值,然后再调用 base.InitializeNewComponent 方法.然后,在调用基本方法之后,再次将 Text 属性设置为默认值.

As an option, you can create and register a new control designer, override InitializeNewComponent and capture the Text property value before calling base.InitializeNewComponent method. Then after calling base method, set the Text property again to the default value.

using System.ComponentModel;
using System.Windows.Forms;
using System.Windows.Forms.Design;
[Designer(typeof(RichTextBoxExDesigner))]
public class RichTextBoxEx : RichTextBox
{
    public RichTextBoxEx ()
    {
        Text = "Some Text";
    }
}
public class RichTextBoxExDesigner : ControlDesigner
{
    public override void InitializeNewComponent(System.Collections.IDictionary defaultValues)
    {
        var txt = Control.Text;
        base.InitializeNewComponent(defaultValues);
        Control.Text = txt;
    }
}

注意:不要忘记添加对 System.Design 程序集的引用.

Note: Don't forget adding reference to System.Design assembly.

旁注:不适用于 Text 属性,但是对于其他类似情况,当您在构造函数中进行设置时看到属性值不被尊重,另一个可疑的原因是 ToolboxItem 的> CreateComponentsCore .对于 Label AutoSize 属性的示例.

Side note: Not for Text property, but for other similar cases which you see a property value is not respected when you set in constructor, another suspect is CreateComponentsCore of ToolboxItem of the control. For example for AutoSize property of the Label.

这篇关于在构造函数中更改扩展的RichTextBox文本不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆