2010-10-08 170 views
2

我有一個類似於this one的問題,但是在更詳細的情況下。我也嘗試使用Model View Viewmodel模式來實現解決方案。綁定到CheckBox並以MVVM方式執行命令

MainView,我有一個按鈕,它調用一個存儲在MainViewModel中的命令(我們稱之爲Execute)。我還希望在單擊鼠標左鍵時調用此命令(實際上,僅在Up上),但僅當選中MouseUpCheckBox時纔會調用該命令。

當我曾在視圖中的所有代碼,我做了靜態的Execute結合,但隨後用ElementName結合Window(名爲w_window)爲IsChecked,並檢查在MouseLeftButtonUpEvent處理程序中的屬性值。

XAML

<Button Command="{x:Static local:MainView.Execute}"> 
    Execute 
</Button> 
<CheckBox IsChecked="{Binding ElementName=w_window, Path=ExecuteOnMouseUp}"> 
    Execute on Mouse Up 
</CheckBox> 

C#

public MainView() 
{ 
    InitializeComponent(); 
    this.CommandBindings.Add(new CommandBinding(Execute, ExecuteExecuted)); 
    MyDesigner.AddHandler(UIElement.MouseLeftButtonUpEvent, new RoutedEventHandler((o, eventArgs) => 
    { 
     if (ExecuteOnMouseUp) 
     { 
      Execute.Execute(null, this); 
     } 
    }), true); 
} 

#region ExecuteOnMouseUp 
/// <summary> 
/// ExecuteOnMouseUp Dependency Property 
/// </summary> 
public static readonly DependencyProperty ExecuteOnMouseUpProperty = 
    DependencyProperty.Register("ExecuteOnMouseUp", typeof(bool), typeof(MainView), 
     new FrameworkPropertyMetadata((bool)false)); 

/// <summary> 
/// Gets or sets the ExecuteOnMouseUp property. This dependency property 
/// indicates .... 
/// </summary> 
public bool ExecuteOnMouseUp 
{ 
    get { return (bool)GetValue(ExecuteOnMouseUpProperty); } 
    set { SetValue(ExecuteOnMouseUpProperty, value); } 
} 
#endregion 

#region Execute 
/// <summary> 
/// The Execute command .... 
/// </summary> 
public static RoutedUICommand Execute 
    = new RoutedUICommand("Execute", "Execute", typeof(MainView)); 

private void ExecuteExecuted(object sender, ExecutedRoutedEventArgs e) 
{ 
    ... 
} 
#endregion 

我怎樣才能從端口我的觀點到視圖模型的代碼?我應該使用附屬物嗎?有沒有辦法將複選框的值綁定到CommandCanExecute處理程序中的參數?處理這種情況的慣用WPF/MVVM方式是什麼?

+0

當我問這個問題時,我不熟悉CommandManager的想法(http://msdn.microsoft.com/en-us/magazine/cc188928.aspx)。我不知道這是否是WPF內置的,但它似乎相關,所以我想在這裏提到它。 – Pat 2013-08-21 17:46:00

回答

2

檢出this文章。它向你展示瞭如何構建一個可以讓你完成你想要做的事情的附加命令。

+0

工程就像一個魅力!但已經過去了5年。現在是否有標準(或PRISM)解決方案? – 2013-08-15 01:47:29

+1

@Klaus你可以使用[Interaction.Triggers](http://coreclr.wordpress.com/2011/01/05/using-interaction-triggers-in-mvvm/),但我通常只使用AttachedCommandBehavior – Rachel 2013-08-15 02:08:13

0

在我看來你的例子看起來有點太複雜,這樣一個簡單的任務,結合按鈕或複選框。

你可能有一個看的WPF Application Framework (WAF)視圖模型示例應用程序。它展示瞭如何以MVVM友好的方式將IsChecked屬性綁定到ViewModel。

0

Rachel提供了一個非常好的解決方案,但爲了理解,我在下面提供了她提到的不同方法的細節(再次感謝@Rachel)。

<... 
xmlns:i="http://schemas.microsoft.com/expression/2010/interactivity" 
...> 
<i:Interaction.Triggers> 
    <i:EventTrigger EventName="ExecuteOnMouseUp"> 
     <i:InvokeCommandAction Command="{Binding Execute}" /> 
    </i:EventTrigger> 
</i:Interaction.Triggers> 

我嘗試了兩種方法,發現在處理路由事件方面存在一些差異。但總的來說,這兩種方法都像魅力一樣運作。