如何同步 WinForms 中 NumericUpDown 和 TrackBar 控件的值?
我有简单的 Windows 窗体应用程序(不是 WPF),并且上面有两个控件:
- TrackBar
- NumericUpDown
我想在它们之间进行一些绑定,因此如果其中一个控件的值发生更改,另一个控件将更新以显示相同的值。
这可能吗?如果是这样,我该怎么办?
谢谢。
I have simple Windows Forms application (not WPF), and I have two controls on it:
- TrackBar
- NumericUpDown
I want to make some binding between them so if one of them has its value change, the other control will be updated to show the same value.
Is this possible? If so, how can I do it?
Thanks.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
当然,这是可能的。我不知道有什么方法可以使两个控件之间自动连接,所以你必须自己编写代码。但别担心,这并不难。
您首先需要将处理程序附加到每个控件在其值更改时引发的事件。从逻辑上讲,两者都控制此事件相同的事情:
ValueChanged
。然后,在每个事件处理程序方法中,您可以以编程方式将另一个控件的值设置为第一个控件的新值。例如:显然,要使其正常工作,您要么需要确保控件具有相同的范围(最大值和最小值),要么向上述代码添加一些错误检查。
Sure, it's possible. I don't know of any way to make the connection between the two controls automatic, so you'll have the write the code yourself. But don't worry, it's not difficult.
You'll first need to attach a handler to the event that is raised by each control when its value changes. Logically enough, both controls this event the same thing:
ValueChanged
. Then, in each event handler method, you can programmatically set the value of the other control to the new value of the first control. For example:Obviously for this to work correctly, you either need to make sure that the controls have the same range (maximum and minimum values), or add some error checks to the above code.
每当其中一个控件导致值发生更改时,其更改值处理程序将导致另一个控件发生更改,然后运行其更改处理程序。但这次值将相同,因此更改处理程序不会再次触发,从而结束潜在的无限循环。
有多种方法可以只触发一名处理程序,但可能不值得。
我将指出,对于轨迹栏控件,使用滚动事件将导致滚动处理程序仅在用户实际移动轨迹栏控件时触发。如果它由于代码而移动(其他控件更改处理程序),则不会触发滚动事件。因此,使用它而不是值更改事件将有助于朝这个方向发展。
另一个方向就有点难了。您必须创建一个数字 up down 派生类并重写 UpButton 和 DownButton 方法以捕获控件本身上的向上和向下箭头的单击。
Ever time one of the controls causes a change in value, its change value handler will cause a change in the other control, followed by its change handler running. But this time the values will be the same so the change handler will not fire again, thus ending a potential endless loop.
There are ways to cause only one handler to fire but they are probably not worth it.
I will point out that for a trackbar control, using the scroll event will cause the scroll handler to fire only when the user actually moves the trackbar control. If it moves as a result of code (the other controls change handler) the scroll event will NOT be triggered. So using it instead of the value changed event will help in that direction.
Its a little harder in the other direction. You would have to create a numeric up down derived class and override the UpButton and DownButton methods to capture the clicking of the up and down arrow on the control itself.