2014-10-27 80 views
2

我很樂意使用ICommand實現處理上的一個按鈕一個動作:的ICommand按鈕按下並釋放在MVVM風格

<Button Command="{Binding Path=ActionDown}">Press Me</Button> 

隨着ICommand正在通過RelayCommand

實現,但我無法找到的是一種簡單的方法,用於爲發佈行爲(包括SO和其他地方的發佈行爲)提供的動作。 IE我想要做的事這一點,但我不知道如何做到這一點:

<Button PressCommand="{Binding Path=ActionDown}" ReleaseCommand="{Binding Path=ActionUp}">Press and Release Me</Button> 

什麼是正確的MVVM的方式來處理這樣的要求?

回答

1

您可以輕鬆地創建自己的類,從Button擴展爲MouseDown和MouseUp定義可綁定的命令。

例子:

public class PressAndReleaseButton : Button 
{ 
    public static readonly DependencyProperty PressCommandProperty = DependencyProperty.Register(
     "PressCommand", typeof(ICommand), typeof(PressAndReleaseButton), new PropertyMetadata(null)); 

    /// <summary> 
    /// The Press command to bind 
    /// </summary> 
    public ICommand PressCommand 
    { 
     get { return (ICommand)GetValue(PressCommandProperty); } 
     set { SetValue(PressCommandProperty, value); } 
    } 

    public static readonly DependencyProperty ReleaseCommandProperty = DependencyProperty.Register(
     "ReleaseCommand", typeof(ICommand), typeof(PressAndReleaseButton), new PropertyMetadata(null)); 

    /// <summary> 
    /// The Release command to bind 
    /// </summary> 
    public ICommand ReleaseCommand 
    { 
     get { return (ICommand)GetValue(ReleaseCommandProperty); } 
     set { SetValue(ReleaseCommandProperty, value); } 
    } 

    /// <summary> 
    /// Default constructor registers mouse down and up events to fire commands 
    /// </summary> 
    public PressAndReleaseButton() 
    { 
     MouseDown += (o, a) => 
       { 
        if (PressCommand.CanExecute(null)) PressCommand.Execute(null); 
       } 
     MouseUp += (o, a) => 
       { 
        if (ReleaseCommand.CanExecute(null)) ReleaseCommand.Execute(null); 
       } 
    } 
} 
+0

我看看你要去哪裏,但是這不會繞過CanEx 'RelayCommand'的一部分? – 2014-10-27 15:35:44

+0

糟糕,我有點太快了。你可以自己調用'CanExecute',讓我更新事件處理程序 – Damascus 2014-10-27 15:43:17

+0

完成。在這種情況下,我假設沒有參數(因此Execute的參數中爲null),但是當然可以使用任何/綁定它們(如創建'PressCommandParameter'依賴項屬性) – Damascus 2014-10-27 15:45:09

4

您可以使用從System.Windows.InteractivityEventTrigger對事件觸發命令

<Button Content="Press Me"> 
    <i:Interaction.Triggers> 
     <i:EventTrigger EventName="PreviewMouseLeftButtonDown"> 
      <i:InvokeCommandAction Command="{Binding Path=ActionDown}"/> 
     </i:EventTrigger> 
     <i:EventTrigger EventName="PreviewMouseLeftButtonUp"> 
      <i:InvokeCommandAction Command="{Binding Path=ActionUp}"/> 
     </i:EventTrigger> 
    </i:Interaction.Triggers> 
</Button> 

你需要添加引用System.Windows.Interactivity並定義命名空間

xmlns:i="http://schemas.microsoft.com/expression/2010/interactivity" 
+0

謝謝你,但是你會如何將它包裝到一個可重用組件中呢?對於一次性按鈕來說很好,但我需要消除大約20個這樣的按鈕,所以我也在尋找方法來最大限度地減少切割和過去。 – 2014-10-27 16:46:06