WPF InputBinding Ctrl + MWheelUp/Down可能吗?

问题描述:

有没有一种方法可以将命令绑定到Ctrl+MWheelUp/Down?你知道在浏览器中,你可以做同样的增加/减少字体大小?我想在WPF中复制该效果。可能?我在看InputBinding>MouseBindingsMouseAction似乎不支持鼠标滚动。WPF InputBinding Ctrl + MWheelUp/Down可能吗?

*我似乎已经张贴了类似的问题,但无法找到它了

好吧,我做了这样的事情在我ShellView : Window

this.KeyDown += (s, e) => 
{ 
    _leftCtrlPressed = (e.Key == Key.LeftCtrl) ? true : false; 
}; 

this.MouseWheel += (s, e) => 
{ 
    if (_leftCtrlPressed) { 
     if (e.Delta > 0) 
      _vm.Options.FontSize += 1; 
     else if (e.Delta < 0) 
      _vm.Options.FontSize -= 1; 
    } 
}; 

我认为行为方法可以让事情变得更清洁,更可重复使用的,但我并没有真正得到它。如果有人在这里以简单的方式解释它会很好吗?

窗口具有MouseWheel事件。您可以执行一些命令绑定魔法,然后您可以绑定到DataContext属性。看看这篇文章的提示:Key press inside of textbox MVVM。也看看这篇文章:http://code.msdn.microsoft.com/eventbehaviourfactor

它可以使用非常简单的定制MouseGesture来完成:

public enum MouseWheelDirection { Up, Down} 

class MouseWheelGesture:MouseGesture 
{ 
    public MouseWheelDirection Direction { get; set; } 

    public MouseWheelGesture(ModifierKeys keys, MouseWheelDirection direction) 
     : base(MouseAction.WheelClick, keys) 
    { 
     Direction = direction; 
    } 

    public override bool Matches(object targetElement, InputEventArgs inputEventArgs) 
    { 
     var args = inputEventArgs as MouseWheelEventArgs; 
     if (args == null) 
      return false; 
     if (!base.Matches(targetElement, inputEventArgs)) 
      return false; 
     if (Direction == MouseWheelDirection.Up && args.Delta > 0 
      || Direction == MouseWheelDirection.Down && args.Delta < 0) 
     { 
      inputEventArgs.Handled = true; 
      return true; 
     } 

     return false; 
    } 

} 

public class MouseWheel : MarkupExtension 
{ 
    public MouseWheelDirection Direction { get; set; } 
    public ModifierKeys Keys { get; set; } 

    public MouseWheel() 
    { 
     Keys = ModifierKeys.None; 
     Direction = MouseWheelDirection.Down; 
    } 

    public override object ProvideValue(IServiceProvider serviceProvider) 
    { 
     return new MouseWheelGesture(Keys, Direction); 
    } 
} 
在XAML

<MouseBinding Gesture="{local:MouseWheel Direction=Down, Keys=Control}" Command="..." /> 

我简单绑定使用Interaction.Triggers命令。

您需要在XAML中引用表达式交互命名空间。

<i:Interaction.Triggers> 
    <i:EventTrigger EventName="PreviewMouseWheel"> 
     <cmd:InvokeCommandAction Command="{Binding MouseWheelCommand}"/> 
    </i:EventTrigger> 
</i:Interaction.Triggers> 

然后在关联的命令中。

private void MouseWheelCommandExecute(MouseWheelEventArgs e) 
    { 
     if (Keyboard.IsKeyDown(Key.LeftCtrl) || Keyboard.IsKeyDown(Key.RightCtrl)) 
     { 
      if (e.Delta > 0) 
      { 
       if (Properties.Settings.Default.ZoomLevel < 4) 
        Properties.Settings.Default.ZoomLevel += .1; 
      } 
      else if (e.Delta < 0) 
      { 
       if (Properties.Settings.Default.ZoomLevel > 1) 
        Properties.Settings.Default.ZoomLevel -= .1; 
      } 
     } 

    } 

如果Delta上升,鼠标向上滚动,下降则向下滚动。我在可滚动内容中出现滚动的应用程序中使用此功能,但当其中一个Ctrl键关闭时,应用程序实际上会进行缩放。