WPF MVVM code for best practice

I am involved in learning C # with WPF using the MVVM pattern. I recently worked on [the art of my application (custom splash screen), which should not close when I don't want it. I searched the web for a good way to do this without code. Unfortunately, after a few days I still have not found a satisfactory way. Then I came up with a way to do it myself, using only one line of code in the constructor of my view. It still makes my code testable and separates the code from the view. The question is, is there a better way to do what I'm trying to do:

My interface for my ViewModel

public interface IPreventCloseViewModel { bool PreventClose { get; set; } } 

Extension for submission

 public static class PreventCloseViewModelExtension { /// <summary> /// Use this extension method in the constructor of the view. /// </summary> /// <param name="element"></param> 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 for submission

 public partial class SplashScreen { public SplashScreen() { InitializeComponent(); this.PreventCloseViewModel(); } } 
+4
c # wpf mvvm code-behind
source share
2 answers

MVVM does not mean that you cannot use Code-Behind.

MVVM means your application logic should not be tied to user interface elements.

You can handle events in the code behind (for example, Window.Closing ) and send messages or execute methods in the ViewModel to react to this.

Here you do not violate MVVM by placing the event handler in the code behind. You break MVVM if you put logic that determines if the application can close in code. This is the responsibility of the application logic, and the application logic lives in ViewModels, not in views.

+14
source share

Usually I have a generic Shell class that subclasses Window and does something like:

 public Shell() { InitializeComponent(); this.Closing += (s,e) => { var canClose = Content as ICanClose; if (canClose != null) e.Cancel = !canClose.CanClose; } } 

Thus, it doesn’t matter which view model you insert if it implements an interface that will be taken into account.

I don’t see much point in externalizing the logic, and that’s good from the point of view of the MVVM pattern.

+4
source share

All Articles