更改文本框文本而不触发TextChanged事件

我在C#中的应用程序有一个带有txt_TextChanged事件的Textbox

 private void txt_TextChanged(object sender, EventArgs e) { //Do somthin } 

但是有一个特定的部分我想在不触发txt_TextChanged事件的情况下更改txt.Text

 txt.Text ="somthing" //Don't fire txt_TextChanged 

我怎样才能做到这一点?

没有直接的方法来阻止为text属性引发事件,但是事件处理程序可以使用标志来确定天气或不执行任务。 这可能比附加和分离事件处理程序更有效。 这可以通过页面中的变量甚至是专门的类包装器来完成

带变量:

 skipTextChange = true; txt.Text = "Something"; protected void TextChangedHandler(object sender, EventArgs e) { if(skipTextChange){ return; } /// do some stuffl } 

使用专门的事件处理器包装器

  var eventProxy = new ConditionalEventHandler(TextBox1_TextChanged); TextBox1.TextChanged = eventProxy.EventAction; eventProxy.RaiseEvents = false; TextBox1.Text = "test"; public void TextBox1_TextChanged(object sender, EventArgs e) { // some cool stuff; } internal class ConditionalEventHadler where TEventArgs : EventArgs { private Action handler; public bool RaiseEvents {get; set;} public ConditionalEventHadler(Action handler) { this.handler = handler; } public void EventHanlder(object sender, TEventArgs e) { if(!RaiseEvents) { return;} this.handler(sender, e); } } 

您可以扩展文本框并在其中引入一个不会触发TextChanged事件的新属性。

  class SilentTextBox : TextBox { // if true, than the TextChanged event should not be thrown private bool Silent { get; set; } public string SilentText { set { Silent = true; Text = value; Silent = false; } } protected override void OnTextChanged(EventArgs e) { // raise event only if the control is in non-silent state if (!Silent) { base.OnTextChanged(e); } } } 
 txt.TextChanged -= textBox1_TextChanged; // dettach the event handler txt.Text = "something"; // update value txt.TextChanged += textBox1_TextChanged; // reattach the event handler 

试试这个扩展方法

  public static class TextBoxExt { private static readonly FieldInfo _field; private static readonly PropertyInfo _prop; static TextBoxExt() { Type type = typeof(Control); _field = type.GetField("text", BindingFlags.Instance | BindingFlags.NonPublic); _prop = type.GetProperty("WindowText", BindingFlags.Instance | BindingFlags.NonPublic); } public static void SetText(this TextBox box, string text) { _field.SetValue(box, text); _prop.SetValue(box, text, null); } } 

您可以使用textbox.SetText(“…”)来更改文本,并且不会触发TextChanged事件。

快速而肮脏的方法是做一个

 ctrl.Enable = false; ctrl.Text = "Something"; ctrl.Enable = true; 

然后在OnChange事件中,使用a封装有问题的代码

 if (ctrl.Enabled) { // offending code here. } 
 public partial class Form1 : Form { public Form1() { InitializeComponent(); EventHandler TextChanged_EventHandler = new EventHandler(textBox1_TextChanged); textBox1.TextChanged -= TextChanged_EventHandler; } private void textBox1_TextChanged(object sender, EventArgs e) { MessageBox.Show("BUG"); } }