2011-10-11 70 views
0

我可以將按鈕和菜單項與ICommand綁定並關閉窗口。 正如教程WPF Apps With The Model-View-ViewModel Design Pattern中所述 - 通過XAML中可訪問的Command屬性。如何在WPF/MVVM右上角的關閉圖標時處理關閉窗口?

但是在教程中沒有描述或實現如何通過按窗口右上角的標準「關閉」圖標來關閉它。我需要在我的應用程序中執行一些清理。 我的問題是如何將Command綁定到關閉事件,以便它在用戶按下關閉圖標(不是按鈕或菜單項 - 我知道如何管理這種情況)時執行。

這應該如何處理以避免違反MVVM方法? 謝謝!

+1

http://www.codewrecks.com/blog/index.php/2011/05/04/event-to-command-in-wpf-mvvm-application/ – michael

回答

2

MVVM Light Toolkit包含一個名爲EventToCommand的行爲,該行爲爲您提供了將命令綁定到事件的簡單方法。

下面的XAML片段顯示獲得一個命令調用如何「CloseCommand」執行時,窗口的關閉事件引發的一個例子:

<Window x:Class="EventToCommand.MainWindow" 
     xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
     xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
     xmlns:i="clr-namespace:System.Windows.Interactivity;assembly=System.Windows.Interactivity" 
     xmlns:cmd="clr-namespace:GalaSoft.MvvmLight.Command;assembly=GalaSoft.MvvmLight.Extras.WPF4" 
    Title="MainWindow" Height="300" Width="500"> 

    <!-- Make sure to put this tag directly inside the Window, 
     and not inside a child element, since it is the Windows that has the Closed event --> 
    <i:Interaction.Triggers> 
     <i:EventTrigger EventName="Closed"> 
      <cmd:EventToCommand Command="{Binding CloseCommand}"/> 
     </i:EventTrigger> 
    </i:Interaction.Triggers> 

    <!-- Windows contents --> 

</Window> 

要訪問的EventToCommand行爲,你需要下載MVVM光工具包從project downloads page,然後引用下列DLL:

  • GalaSoft.MvvmLight.dll
  • GalaSoft.MvvmLight.Extras.dll
  • System.Windows.Interactivity.dll

這就是所有需要的。

關於如何開始使用工具包的進一步說明可以在here找到。

+0

謝謝埃裏克。我現在知道的主要事情是沒有簡單的解決方案,如果沒有MS的頭像......就像往常一樣......並感謝問題澄清:) – sergtk

2

我將命令綁定到應用程序的退出事件

我喜歡用AttachedCommand行爲發現here綁定命令到活動,雖然我知道你也可以使用混合的互動觸發完成同樣的事情。