title: WPF MVVM Code Behind Best Practices
body: <p>I'm a student learning C# with WPF using the MVVM pattern. Recently I have been working on a [art of my application (a custom splash screen) that should not be closed when I don't want it to.
  I have been searching the web for a good way of doing this without code-behind. Unfortunately after days I still did not find a satisfying way.
  Then I came to think of a way to do it myself, with help of just one line of code in the constructor of my view. It still makes my code testable and decouples the code from the View. The question is, is there a better way of doing what I'm trying to do:</p>
  
  <p>My interface for my ViewModel</p>
  
  <pre><code>public interface IPreventCloseViewModel
  {
      bool PreventClose { get; set; }
  }
  </code></pre>
  
  <p>The extension for the View</p>
  
  <pre><code>public static class PreventCloseViewModelExtension
  {
      /// &lt;summary&gt;
      /// Use this extension method in the constructor of the view.
      /// &lt;/summary&gt;
      /// &lt;param name="element"&gt;&lt;/param&gt;
      public static void PreventCloseViewModel(this Window element)
      {
          var dataContext = element.DataContext as IDisposable;
          if (dataContext is IPreventCloseViewModel)
          {
              element.Closing += delegate(object sender, CancelEventArgs args)
                                     {
                                         if (dataContext is IPreventCloseViewModel)
                                         {
                                             args.Cancel = (dataContext as IPreventCloseViewModel).PreventClose;
                                         }
                                     };
          }
      }
  }
  </code></pre>
  
  <p>The code-behind for the View</p>
  
  <pre><code>public partial class SplashScreen
  {
      public SplashScreen()
      {
          InitializeComponent();
          this.PreventCloseViewModel();
      }
  }
  </code></pre>