在 WPF 自定义控件中处理 MouseWheel 事件
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14340937/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Handling MouseWheel event in a WPF custom control
提问by Seb
I have am making a map editor for a game which has a user control that has an image. Inside that control I attached the MouseWheelevent to it, but I've noticed two issues that I hope to have a better understanding of why it behaves the way it does and how to properly implement it.
我正在为具有图像的用户控件的游戏制作地图编辑器。在该控件中,我将MouseWheel事件附加到了它,但我注意到了两个问题,我希望能够更好地理解为什么它的行为方式以及如何正确实现它。
For one the event only seems to fire when the mouse is hovering over it instead of when the control is in focus. If possible I would like to switch that and be able to fire the event no matter where the mouse is as long as that control is in focus and the second issue is that checking the delta when the number is positive works fine, but when I get a number back when it's negative I get a value of 0xfffffffd or something in that range. How would I go about differentiating the difference between a positive balue and a negative value if I always get something positive?
对于一个事件,似乎只有当鼠标悬停在它上面时才会触发,而不是在控件处于焦点时触发。如果可能的话,我想切换它并且无论鼠标在哪里都能够触发事件,只要该控件处于焦点中,第二个问题是当数字为正时检查增量工作正常,但是当我得到当它是负数时返回一个数字,我得到 0xfffffffd 或该范围内的值。如果我总是得到一些积极的东西,我将如何区分正值和负值之间的差异?
Thanks in advance for the help.
在此先感谢您的帮助。
回答by Rafal
If you want to fire MouseWheelevent for focused element try:
如果要MouseWheel为焦点元素触发事件,请尝试:
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
this.MouseWheel += OnMouseWheel;
}
IInputElement focusedElement;
private void OnMouseWheel(object sender, MouseWheelEventArgs e)
{
if (focusedElement is TextBox)
{
var tbx = focusedElement as TextBox;
//do something
}
}
protected override void OnPreviewLostKeyboardFocus(KeyboardFocusChangedEventArgs e)
{
focusedElement = e.NewFocus;
}
}

