because it is very simple, the blog is not much to write, download the project to see the code that you can understand .
Since we want to separate the front and back, we should not directly manipulate the view window in the ViewModel, we can use data binding method to manipulate it, to bind a window to a state property, 1 o'clock close the window.
It is not possible to manually add this property to each window in the development process, so create a new class , Inherit the window, add a dependency property to the class to determine if the window should be closed, and then use the class for all windows.
(The normal attribute cannot be bound and requires a dependency property.)
TmdWindow.cs
usingSystem;usingSystem.Collections.Generic;usingSystem.Linq;usingSystem.Text;usingSystem.Threading.Tasks;usingSystem.Windows;namespacetmdmvvm{ Public classTmdwindow:window {#regiondependency property#regionWindow state/// <summary> ///window State (bindable property) is 1 o'clock closed/// </summary> Public intWstate {Get{return(int) GetValue (Wstateproperty); } Set{SetValue (wstateproperty, value); } } Public Static ReadOnlyDependencyProperty Wstateproperty =Dependencyproperty.register ("wstate",typeof(int),typeof(Tmdwindow),NewPropertyMetadata (defaultvalue:0, Propertychangedcallback:wstatepropertychangedcallback, Coercevaluecallback: /c1>NULL) ); Private Static voidWstatepropertychangedcallback (DependencyObject D, DependencyPropertyChangedEventArgs e) {Tmdwindow C= (d asTmdwindow); if(c! =NULL) { if(E.newvalue! =NULL) { intv =Convert.ToInt32 (E.newvalue); Switch(v) { Case 1: //Close WindowC.close (); Break; } } } } #endregion #endregion }}
Using and binding State properties on a window
<Local:tmdwindowx:class= "TMDMVVM." MainWindow "xmlns= "Http://schemas.microsoft.com/winfx/2006/xaml/presentation"xmlns:x= "Http://schemas.microsoft.com/winfx/2006/xaml"xmlns:d= "http://schemas.microsoft.com/expression/blend/2008"XMLNS:MC= "http://schemas.openxmlformats.org/markup-compatibility/2006"xmlns:local= "CLR-NAMESPACE:TMDMVVM"mc:ignorable= "D"Title= "MainWindow"Height= " the"Width= "525"wstate="{Binding Wstate}" > <TextBlockText= "This window will be closed after 3 seconds"></TextBlock></Local:tmdwindow>
Here is a hurry to omit a lot of code, the window closed directly with a thread delay 3 seconds to set the state properties, ViewModel code
usingSystem;usingSystem.Collections.Generic;usingSystem.Linq;usingSystem.Text;usingSystem.Threading;usingSystem.Threading.Tasks;namespaceTMDMVVM. viewmodel{ Public classtmdviewmodel:uinotifypropertychanged {Private intWstate_; Public intwstate {Get{returnWstate_; }Set{Wstate_ =value; OnPropertyChanged (); } } PublicTmdviewmodel () {Thread T=NewThread (() = { //Sleep 3 secondsThread.Sleep ( the); //Close WindowWstate =1; }); T.start (); } }}
Fix It ~
Project Download:
Click I download
C # WPF MVVM more conforms to the pattern concept of the Close view window method