我正在寻找一个巧妙的解决方案来临时取消订阅 WinForm 事件。例如,如果我有一个带有以下事件处理程序的 textBox1 控件:
private void textBox1_TextChanged(object sender, EventArgs eventArgs)
{
// Do something
}
当我以编程方式更改文本框的内容时,我不希望触发此事件。但不是写:
try
{
textBox1.TextChanged -= textBox1_TextChanged;
// Change textbox contents without triggering event
}
finally
{
textBox1.TextChanged += textBox1_TextChanged;
}
我正在寻找可以使用类似于此的东西:
using(new EventInhibitor(textBox1.TextChanged, textBox1_TextChanged))
{
// Change textbox contents without triggering event
}
问题是如何将 textBox1.TextChanged 事件传递给构造函数?反射?表达式?
public class EventInhibitor : IDisposable
{
private bool _disposed = false;
private XXX _event;
private EventHandler _handler;
public EventInhibitor(XXX event, EventHandler handler)
{
_event = event;
_handler = handler;
_event -= _handler;
}
public void Dispose()
{
if(_disposed)
return:
_event += _handler;
_event = null;
_handler = null;
_disposed = true;
}
}