使用InputBindings WPF检测三次单击

时间:2018-03-11 10:24:24

标签: c# wpf xaml

我需要检测ViewModel中Image元素的三次点击。

所以我在我的视图中有这个

  <Image MouseDown="Image_MouseDown"  Margin="0 0 20 0" Source="..." HorizontalAlignment="Right"  >
     <Image.InputBindings>
        <MouseBinding MouseAction="LeftDoubleClick" Command="{Binding MouseDoubleClickCommand}"/>
     </Image.InputBindings>
  </Image>

我的ViewModel中的代码:

     public ICommand MouseDoubleClickCommand { get; } = new RelayCommandParametrized(obj =>
     {

           // Detect here triple click
    });

问题是ClickCount存在于MouseButtonEventArgs中,无法在viewmodel中找到我的方法。

有什么建议吗?

2 个答案:

答案 0 :(得分:1)

所以,我喜欢ReactiveExtensions,我将使用它们。看看ReactiveUI

首先,您需要使用reactiveui-events nuget包。

然后,创建扩展方法:

 public static IObservable<Unit> TripleClick(this ButtonBase element, int totalMillisecondsLimit = 1000)
    {
        return element.Events().Click // get clicks
             .Select(x => Unit.Default).TimeInterval().Select(x => x.Interval) // get time intervals between them
             .Window(3) // always look at last 3
             .SelectMany(x => x.ToArray()) // just make array from observable produced by Window
             .Where(x => x.Skip(1).Sum(z => z.TotalMilliseconds) < totalMillisecondsLimit) // check if the 3 clicks are very close to each other
             .Select(x => Unit.Default); // you can return whatever you want, Unit.Default is Reactive version of void
    }

然后在您的视图的xaml.cs中,您可以使用以下内容:

 Button.TripleClick().Subscribe(click =>
            {

            });

            // or

  Button.TripleClick().InvokeCommand(ViewModel.SomeCommand);

请注意,在WPF中,您应该处置这些订阅。优选地,通过使用WhenActivated

说实话,我相信您可以将其包装在WPF交互或行为中,然后能够绑定到XAML中的TripleClick。

答案 1 :(得分:-2)

您需要实施互动触发器。

在XAML中添加引用

xmlns:i="clr-namespace:System.Windows.Interactivity;assembly=System.Windows.Interactivity" 
xmlns:cmd="clr-namespace:GalaSoft.MvvmLight.Command;assembly=GalaSoft.MvvmLight.Extras.WPF4"

<Image MouseDown="Image_MouseDown"  Margin="0 0 20 0" Source="..." HorizontalAlignment="Right"  >

<i:Interaction.Triggers>
    <i:EventTrigger EventName="LeftDoubleClick" >
         <cmd:EventToCommand Command="{Binding MouseDoubleClickCommand}"
             PassEventArgsToCommand="True" />
    </i:EventTrigger>
</i:Interaction.Triggers>