Sunday, November 12, 2017

The quick and dirty for using System.Windows.Interactivity and the MVVM pattern for custom dialogs in your WPF application

So I recently decided to finally try my hand at using proper MVVM patterns with my custom dialogs in the application on which I'm currently working (started back in 2010 before a lot of MVVM frameworks existed). I followed Microsoft's Interactivity Getting-started guide here. The quick summary of steps to take (as a reminder) are below. That said, read the article tip-to-tail so that you understand these steps, and then use this page as a reminder.


  1. For your dialog (e.g. MyDialog), you'll need to create the following items:
    • MyDialogViewModel, which implements Prism.Interactivity.InteractionRequest.IInteractionRequestAware
    • MyDialogConfirmation, which extends from Prism.Interactivity.InteractionRequest.Confirmation
  2. In your dialog, ensure that it extends from System.Windows.Control.UserControl, NOT System.Windows.Window (because your interactivity request handler in XAML needs a control for its Content, not a Window)
  3. In the constructor of your Dialog user control, set your data context to a new instance of your MyDialogViewModel (to ensure that it's present in the DataContext when the Interactivity framework invokes your dialog's window and can inject it with your MyDialogConfirmation instance when you raise the notification for your InteractivityRequest to which you're binding
  4. Ensure you've created your interactivity handler in the XAML of the view that's calling your dialog, e.g.:
 <i:Interaction.Triggers>
  <prism:InteractionRequestTrigger SourceObject="{Binding Path=MyDialogInteractivityRequestProperty, Mode=OneWay}">
   <prism:PopupWindowAction IsModal="True" CenterOverAssociatedObject="True">
    <prism:PopupWindowAction.WindowContent>
     <Dialogs:MyDialog />
    </prism:PopupWindowAction.WindowContent>
   </prism:PopupWindowAction>
  </prism:InteractionRequestTrigger>
 </i:Interaction.Triggers>

No comments:

Post a Comment