开发者

WPF correct way to set a bool while a key is pressed

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 Ke开发者_如何学PythonyEventHandler(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?


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.


Have a look at AttachedCommandBehavior library and examples provided

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜