UserControl中的文本更改事件未在Windows应用程序中触发

时间:2017-11-17 10:56:14

标签: c#

我使用文本框创建一个usercontrol。但文本框文本changedevent不存在。所以我在用户控件中添加了textschanged事件。文本更改代码在proerties窗口中列出,但它不起作用(触发)。

    using System;
    using System.Collections.Generic;
    using System.ComponentModel;
    using System.Drawing;
    using System.Data;
    using System.Linq;
    using System.Text;
    using System.Windows.Forms;

    namespace TextBoxBorederUserControl
    {
    public partial class UserControl1 : UserControl
    {
    public event EventHandler TextBoxTextChanged;
    TextBox textBox;
    public void HandleTextBoxTextChanged(object sender, EventArgs e)
    {
        this.OnTextChanged(EventArgs.Empty);
    }
    protected virtual void OnTextBoxTextChanged(EventArgs e)
    {
        EventHandler handler = this.TextBoxTextChanged;
        if (handler != null)
        {
            handler(this,e);
        }

    }

        public UserControl1()
        {
            textBox = new TextBox()
            {
                BorderStyle = BorderStyle.FixedSingle,
                Multiline   = true,

                Location = new Point(-1, -1),
                Anchor = AnchorStyles.Top | AnchorStyles.Bottom |
                         AnchorStyles.Left | AnchorStyles.Right
            };
            textBox.TextChanged += this.HandleTextBoxTextChanged;
            Control container = new ContainerControl()
            {
                Dock = DockStyle.Fill,
                Padding = new Padding(-1)
            };
            container.Controls.Add(textBox);
            this.Controls.Add(container);
            FocusedBorderColor = System.Drawing.ColorTranslator.FromHtml("#66AFE9");////BLUE
            DefaultBorderColor = System.Drawing.ColorTranslator.FromHtml("#F1F1F1");///////////////////GRAY




            BackColor = DefaultBorderColor;
            Padding = new Padding(1);
            Size = textBox.Size;
        }

        public Color DefaultBorderColor { get; set; }

        public Color FocusedBorderColor { get; set; }

        public override string Text
        {
            get { return textBox.Text; }
            set { textBox.Text = value; }
        }

        protected override void OnEnter(EventArgs e)
        {
            BackColor = FocusedBorderColor;
            base.OnEnter(e);
        }

        protected override void OnLeave(EventArgs e)
        {
            BackColor = DefaultBorderColor;
            base.OnLeave(e);
        }

        protected override void SetBoundsCore(int x, int y,
            int width, int height, BoundsSpecified specified)
        {
            base.SetBoundsCore(x, y, width, textBox.PreferredHeight, specified);
        }

}
    }

我使用文本框创建一个usercontrol。但文本框文本changedevent不存在。所以我在用户控件中添加了textschanged事件。文本更改代码在proerties窗口中列出,但它不起作用(触发)。

1 个答案:

答案 0 :(得分:0)

试试这个:

public void HandleTextBoxTextChanged(object sender, EventArgs e)
{
    this.OnTextBoxTextChanged(EventArgs.Empty);
}