且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

在跟踪栏ValueChanged上触发事件,但在代码中未触发

更新时间:2023-12-03 13:11:16

执行此操作的一种方法是在修改代码中的值之前临时删除事件处理程序,然后再重新附加它们,尽管这似乎并不可行.太优雅了.

One way you can do this is to temporarily remove the event handlers before you modify the values in code, and then reattach them afterwards, although this doesn't seem too elegant.

或者,您可以创建自己的自定义TrackBar类,该类继承自TrackBar,并重写OnValueChanged()方法以执行所需的操作.

Alternatively you could create your own custom TrackBar class that inherits from TrackBar and override the OnValueChanged() method to do what you want.

如果您这样做,我可以想到的一个想法是在更改值之前设置SuspendChangedEvents属性,然后再对其进行重置,这将提供与删除/附加"处理程序技术类似的功能,但逻辑封装在其中TrackBar本身.

If you did this, an idea I can think of is to set a SuspendChangedEvents property before changing the value, and reset it afterwards, This would provide similar functionality to the 'remove/attach' handler technique but the logic is encapsulated within the TrackBar itself.

public class MyTrackBar : TrackBar
{
    public bool SuspendChangedEvent
    { get; set; }

    protected override void OnValueChanged(EventArgs e)
    {
        if (!SuspendChangedEvent) base.OnValueChanged(e);
    }
}

然后在您的代码中,您可以执行以下操作.

Then in your code you can do something like this.

// Suspend trackbar change events
myTrackBar1.SuspendChangedEvents = true;

// Change the value
myTrackBar1.Value = 50;  // ValueChanged event will not fire.

// Turn changed events back on
myTrackBar1.SuspendChangedEvents = false;