Search code examples
wpfeventsbuttonkeypress

Using enter to click a button


Basically I'd like to give Enter the same behavior Space has. First issue I was facing was that when holding key the button would keep on on firing off. I solved that by listening for PreviewKeyDown and marking it as handled when the IsRepeat property was true.

The second issue I cannot wrap my head around is that Trigger which uses IsPressed doesn't go off upon pressing Enter. Here's the trigger.

<Trigger Property="IsPressed"
         Value="True">
    <Setter TargetName="Background"
            Property="Background"
            Value="{DynamicResource ButtonPressedBrush}" />
</Trigger>

Is Enter somehow special? The button does get clicked, but the trigger doesn't get actived.


Solution

  • In accord with this:

    IsPressed is the state of a button that indicates the left mouse button or SPACEBAR is pressed over the button. When IsPressed is true, the control captures the mouse. As a result, the control will raise mouse events such as MouseEnter and IsMouseDirectlyOverChanged. Note that using the AccessText or ENTER does not change IsPressed or capture the mouse, but is does raise the Click event.

    I.e., behavior of your control is OK.

    I'd not recommend you to change it, but if you want, you should:

    • create new class (for example, ButtonEx)
    • inherit it from Button or ButtonBase
    • subscribe KeyDown routed event (in constructor or somewhere else) OR override OnKeyDown
    • subscribe KeyUp routed event (in constructor or somewhere else) OR override OnKeyUp
    • implement behavior you want, i.e. check that Enter is pressed on key down and is released on key up and change IsPressed correspondingly

    Hope, it helps