WPF 在按下按键时设置布尔值的正确方法
在 WPF 中,我需要在按下按键时设置一个布尔变量(并另外执行一些其他操作)。即按下该键即可设置,松开该键即可复位。我可以通过事件处理程序完成一些事情:
this.KeyDown += new KeyEventHandler(MyModuleView_KeyDown);
this.KeyUp += new KeyEventHandler(MyModuleView_KeyUp);
bool MyFlag = false;
void MyModuleView_KeyUp(object sender, KeyEventArgs e)
{
if (e.Key == System.Windows.Input.Key.Space)
{
MyFlag = false;
...
}
}
void MyModuleView_KeyDown(object sender, KeyEventArgs e)
{
if (e.Key == System.Windows.Input.Key.Space)
{
MyFlag = true;
...
}
}
但我怀疑在 WPF 中可以通过更正确的方式完成。
我正在尝试使用命令方法,但在我这样做的方式中,我只能设置一个变量事实上按下一个键,而不是当一个键是Pressed.:
private static RoutedUICommand mymode;
InputGestureCollection inputs = new InputGestureCollection();
inputs.Add(new KeyGesture(Key.Space, "Space"));
mymode = new RoutedUICommand("MyMode", "MyMode", typeof(InterfaceCommands), inputs);
public static RoutedUICommand MyMode
{
get { return mymode; }
}
...
private void MyModeCommand_Executed(object sender, ExecutedRoutedEventArgs e)
{
MyFlag = true;
...
}
如何在按下按键时正确跟踪 WPF 中按键的状态以打开某些内容(例如光标的选择模式)?
I WPF I need to set a boolean variable (and additionally perform some other actions) while a key is pressed. I.e. to set on the key is pressed, and to reset on the key is released. Something that I can do by just event handlers:
this.KeyDown += new KeyEventHandler(MyModuleView_KeyDown);
this.KeyUp += new KeyEventHandler(MyModuleView_KeyUp);
bool MyFlag = false;
void MyModuleView_KeyUp(object sender, KeyEventArgs e)
{
if (e.Key == System.Windows.Input.Key.Space)
{
MyFlag = false;
...
}
}
void MyModuleView_KeyDown(object sender, KeyEventArgs e)
{
if (e.Key == System.Windows.Input.Key.Space)
{
MyFlag = true;
...
}
}
But I suspect in WPF it can be done in a more correct way.
I'm trying to use a command approach, but in the way I do it I can only set a variable on the fact of pressing a key but not while a key is pressed.:
private static RoutedUICommand mymode;
InputGestureCollection inputs = new InputGestureCollection();
inputs.Add(new KeyGesture(Key.Space, "Space"));
mymode = new RoutedUICommand("MyMode", "MyMode", typeof(InterfaceCommands), inputs);
public static RoutedUICommand MyMode
{
get { return mymode; }
}
...
private void MyModeCommand_Executed(object sender, ExecutedRoutedEventArgs e)
{
MyFlag = true;
...
}
How to correctly track the state of a key in WPF for turning on something (for example selection mode of a cursor) while the key is pressed?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
命令在这里对你没有帮助,你处理事件的方法才是正确的方法。如果您不喜欢隐藏代码 - 您可以创建一个自定义附加属性,它将负责事件连接。
Commands will not help you here, your approach with events is a right way to go. If you don't like to have a code-behind - you can create a custom attached property, which would be responsible for events wiring.
查看 AttachedCommandBehavior 库 和提供的示例
Have a look at AttachedCommandBehavior library and examples provided