14

我想在触摸特定键时使用 EventTrigger 调用命令(例如,空格键)

目前我有:

  <i:Interaction.Triggers>
       <i:EventTrigger EventName="KeyDown">
            <i:InvokeCommandAction Command="{Binding DoCommand}" CommandParameter="{BindingText}"/>
       </i:EventTrigger>
  </i:Interaction.Triggers>

现在,我如何指定仅在 KeyDown 与空格键一起出现时才发生这种情况?

4

3 回答 3

15

您必须构建一个自定义触发器来处理它:

public class SpaceKeyDownEventTrigger : EventTrigger {

    public SpaceKeyDownEventTrigger() : base("KeyDown") {
    }

    protected override void OnEvent(EventArgs eventArgs) {
        var e = eventArgs as KeyEventArgs;
        if (e != null && e.Key == Key.Space)
            this.InvokeActions(eventArgs);
    }
}
于 2011-10-17T19:51:35.173 回答
15

另一种方法是使用 KeyBindings 并将它们绑定到您的 Window、UserControl、FrameworkElement 等。这不会触发按钮,但假设您有一个从按钮调用的命令“MyCommand”,您可以从 InputBindings 调用命令.

<UserControl.InputBindings>
   <KeyBinding Command="{Binding Path=ApplyCommand}" Key="Enter"/>
   <KeyBinding Command="{Binding Path=NextPage}" Modifiers="Ctrl" Key="Left"/>
</UserControl.InputBindings>

<StackPanel> 
    <Button IsDefault="True" Content="Apply">
        <i:Interaction.Triggers>
           <i:EventTrigger EventName="Click">
               <i:InvokeCommandAction Command="{Binding Path=ApplyCommand}" />                            
           </i:EventTrigger>
        </i:Interaction.Triggers>
    </Button>
 </StackPanel>

您还可以将这些 KeyBindings 绑定到 TextBox。

于 2015-11-17T13:39:16.590 回答
1

我喜欢带有自定义触发器的想法,但我没有设法使其工作(某些方法已更改或不推荐使用,因此上面显示的定义SpaceKeyDownEventTrigger现在未编译)。所以,我把自定义的工作版本放在这里RoutedEventSpaceKeyDownEvent是在MyControl自定义控件中定义的,并且在到达未处理的附加事件并且按下的键是空格键时从方法OnKeyDownKeyDown引发MyControl

public class MyControl : ContentControl
{
    // This constructor is provided automatically if you
    // add a Custom Control (WPF) to your project
    static MyControl()
    {
        DefaultStyleKeyProperty.OverrideMetadata(
            typeof(MyControl),
            new FrameworkPropertyMetadata(typeof(MyControl)));
    }

    // Create a custom routed event by first registering a RoutedEventID
    // This event uses the bubbling routing strategy
    public static readonly RoutedEvent SpaceKeyDownEvent = EventManager.RegisterRoutedEvent(
        "SpaceKeyDown",
        RoutingStrategy.Bubble,
        typeof(RoutedEventHandler),
        typeof(MyControl));

    // Provide CLR accessors for the event
    public event RoutedEventHandler SpaceKeyDown
    {
        add { AddHandler(SpaceKeyDownEvent, value); }
        remove { RemoveHandler(SpaceKeyDownEvent, value); }
    }

    // This method raises the SpaceKeyDown event
    protected virtual void RaiseSpaceKeyDownEvent()
    {
        RoutedEventArgs args = new RoutedEventArgs(SpaceKeyDownEvent);
        RaiseEvent(args);
    }

    // Here KeyDown attached event is customized for the desired key
    protected override void OnKeyDown(KeyEventArgs e)
    {
        base.OnKeyDown(e);

        if (e.Key == Key.Space)
            RaiseSpaceKeyDownEvent();
    }
}

MyControl可以添加到另一个控件的模板中,允许后者与EventTrigger路由SpaceKeyDown事件一起使用:

<Style TargetType="{x:Type local:MyControl}">
        <Setter Property="Template">
            <Setter.Value>
                <ControlTemplate TargetType="{x:Type local:MyControl}">
                    <Grid>
                        <ContentPresenter/>
                    </Grid>
                </ControlTemplate>
            </Setter.Value>
        </Setter>
    </Style>

    <!-- Adding MyControl to the TextBox template -->
    <Style TargetType="{x:Type TextBox}">
        <Setter Property="Template">
            <Setter.Value>
                <ControlTemplate TargetType="{x:Type TextBox}">
                    <Border x:Name="border" BorderBrush="{TemplateBinding BorderBrush}" BorderThickness="{TemplateBinding BorderThickness}" Background="{TemplateBinding Background}" SnapsToDevicePixels="True">
                        <local:MyControl>
                            <ScrollViewer x:Name="PART_ContentHost" Focusable="false" HorizontalScrollBarVisibility="Hidden" VerticalScrollBarVisibility="Hidden"/>
                        </local:MyControl>
                    </Border>
                </ControlTemplate>
            </Setter.Value>
        </Setter>
        <Style.Triggers>
            <EventTrigger RoutedEvent="local:MyControl.SpaceKeyDown">
                <BeginStoryboard>
                    <Storyboard>
                        <ColorAnimation Storyboard.TargetProperty="Foreground.Color"
                                                    From="White" To="Transparent" Duration="0:0:0.066" AutoReverse="True" RepeatBehavior="3x"/>
                    </Storyboard>
                </BeginStoryboard>
            </EventTrigger>
        </Style.Triggers>
    </Style>
于 2018-08-25T19:57:33.733 回答