繁体   English   中英

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

[英]How to expose TextBox Text Property in a User Control

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

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

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

除了一个例外,一切似乎都运行良好。 当我将控件放在窗体上时,TextBox 会显示控件的名称,即控件 1。我尝试将属性默认属性设置如下,但没有影响。

DefaultValue((string)null),

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

感谢您提供任何指导的建议。

此问题的解决方案是自定义ParentControlDesigner ,您可以在其中重写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 = "";
        }
    }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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