我在 C#
中的应用程序有一个带有 txt_TextChanged
事件的 Textbox
.
My application in C#
has a Textbox
with a txt_TextChanged
event.
private void txt_TextChanged(object sender, EventArgs e)
{
//Do somthin
}
但有一个特定部分我想更改 txt.Text
而不触发 txt_TextChanged
事件.
But there's one specific part that I want to change txt.Text
without firing the txt_TextChanged
event.
txt.Text ="somthing" //Don't fire txt_TextChanged
我该怎么做?
没有直接的方法来阻止 text 属性引发事件,但是您的事件处理程序可以使用标志来确定天气或不执行任务.这可能比附加和分离事件处理程序更有效.这可以通过页面中的变量甚至专门的类包装器来完成
There is no direct way to prevent the raising of events for the text property, however your event handler can use a flag to determine weather or not to perform a task. This i likely to be more efficient than attaching and detaching the event handler. This can be done by a variable within the page or even a specialized class wrapper
带变量:
skipTextChange = true;
txt.Text = "Something";
protected void TextChangedHandler(object sender, EventArgs e) {
if(skipTextChange){ return; }
/// do some stuffl
}
使用专门的事件处理程序包装器
With specialized event handler wrapper
var eventProxy = new ConditionalEventHandler<EventArgs>(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<TEventArgs> where TEventArgs : EventArgs
{
private Action<object,TEventArgs> handler;
public bool RaiseEvents {get; set;}
public ConditionalEventHadler(Action<object, TEventArgs> handler)
{
this.handler = handler;
}
public void EventHanlder(object sender, TEventArgs e) {
if(!RaiseEvents) { return;}
this.handler(sender, e);
}
}
这篇关于在不触发 TextChanged 事件的情况下更改文本框文本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!