如何在用户控件中公开 TextBox 文本 属性

How to expose TextBox Text Property in a User Control

我希望有人可以帮助我确定我一定是一个愚蠢的错误。

我已将我正在处理的用户控件拆分为基本元素。我在用户控件上放置了一个文本框并公开文本框文本 属性 我创建了以下内容

[Browsable(true)]
    public override string Text 
    { 
        get
        {
            return textBox1.Text;
        }
        
        set
        {
            textBox1.Text = value;
        }
    
    }

似乎一切正常,只有一个例外。当我将控件放在窗体上时,文本框会显示控件的名称,即控件 1。 我试过如下设置属性默认属性不影响。

DefaultValue((string)null),

如何停止控件显示控件名称?

感谢您的建议。

此问题的解决方案是自定义 ParentControlDesigner where you can override the InitializeNewComponent 方法来设置或清除 Text 属性。

例子

using System;
using System.Collections;
using System.ComponentModel;
using System.Windows.Forms;
using System.Windows.Forms.Design;
using System.Security.Permissions;

namespace YourProject
{
    [DefaultProperty(nameof(Text))]
    [DefaultEvent(nameof(TextChanged))]
    [Designer(typeof(MyUserControlDesigner))]
    public partial class MyUserControl : UserControl
    {
        public MyUserControl()
        {
            InitializeComponent();

            // Update the base.Text whenever the TextBox.Text property is changed.
            textBox1.TextChanged += (s, e) =>
            {
                if (textBox1.Text != Text) Text = textBox1.Text;
            };
        }

        // Get and set the text of the base property instead of the TextBox's
        // to get the TextChanged event raised.
        [Browsable(true),
            EditorBrowsable(EditorBrowsableState.Always),
            DesignerSerializationVisibility(DesignerSerializationVisibility.Visible)]
        public override string Text
        {
            get => base.Text;
            set => base.Text = value;
        }

        protected override void OnTextChanged(EventArgs e)
        {
            // Update the TextBox.Text property whenever the base property is changed.
            if (Text != textBox1.Text) textBox1.Text = Text;
            base.OnTextChanged(e);
        }

        // If you need to handle the TextChanged event...
        /// <inheritdoc cref="Control.TextChanged"/>
        [Browsable(true), EditorBrowsable(EditorBrowsableState.Always)]
        public new event EventHandler TextChanged
        {
            add { base.TextChanged += value; }
            remove { base.TextChanged -= value; }
        }
    }

    [PermissionSet(SecurityAction.Demand, Name = "FullTrust")]
    public class MyUserControlDesigner : ParentControlDesigner
    {
        public override void InitializeNewComponent(IDictionary defaultValues)
        {
            base.InitializeNewComponent(defaultValues);

            if (Component is MyUserControl c) c.Text = "StephenH"; // c.Text = "";
        }
    }
}