2014-09-11 77 views
2

目前,我正在學習WPF/MVVM,並一直使用以下問題的代碼顯示使用對話框服務(包括朱利安·多明格斯布爾改變)對話框:MVVM,DialogService和對話結果

Good or bad practice for Dialogs in wpf with MVVM?

顯示一個對話框,效果很好,但是對話的結果總是儘管實際上正在顯示的對話框中的事實錯誤。我DialogViewModel目前是空的,我想,也許我需要我的DialogViewModel「掛鉤」的RequestCloseDialog事件。是這樣嗎?

回答

1

貴DialogViewmodel實現IDialogResultVMHelper?並且你的View/DataTemplate有一個綁定到你的DialogViewmodel的命令來引發RequestCloseDialog?

public class DialogViewmodel : : INPCBase, IDialogResultVMHelper 
    { 
     private readonly Lazy<DelegateCommand> _acceptCommand; 

    public DialogViewmodel() 
    { 
     this._acceptCommand = new Lazy<DelegateCommand>(() => new DelegateCommand(() => InvokeRequestCloseDialog(new RequestCloseDialogEventArgs(true)),() => **Your Condition goes here**)); 
    } 

    #region Implementation of IDialogResultVMHelper 

    public event EventHandler<RequestCloseDialogEventArgs> RequestCloseDialog; 

    private void InvokeRequestCloseDialog(RequestCloseDialogEventArgs e) 
    { 
     var handler = RequestCloseDialog; 
     if (handler != null) 
      handler(this, e); 
    } 

    #endregion 
} 

在對話框控制的任何地方:

<StackPanel Grid.Row="2" Orientation="Horizontal" HorizontalAlignment="Right" MinHeight="30"> 
     <Button IsDefault="True" Content="Übernehmen" MinWidth="100" Command="{Binding AcceptCommand}"/> 
     <Button IsCancel="True" Content="Abbrechen" MinWidth="100"/> 
    </StackPanel> 

,然後你的結果應該在您的視圖模型

  var dialog = new DialogViewmodel(); 
      var result = _dialogservice.ShowDialog("My Dialog", dialog); 

      if(result.HasValue && result.Value) 
      { 
       //accept true 
      } 
      else 
      { 
       //Cancel or false 
      } 
+0

謝謝合作!這很好用!另外我介紹了Lazy-Loading的世界! – bdan 2014-09-12 00:38:27