WPF framework MVVM Simple Example

Source: Internet
Author: User

MVVM is an abbreviated form of Model-view-viewmodel, which is commonly used for WPF or Silverlight development.
Model--a class that can be understood as a property with a field.
View--can be understood as the UI we see.
The view Model acts as a connection between the view and the model, and separates the view from the model layer. The view model is not just a model wrapper, it also contains the program logic and the model extension, for example, if there is a public property in the model that does not need to be displayed on the UI, then we can no longer define it in the view model.

In MVVM, the status of VMS can be said to be pivotal. Using the MVVM pattern has several features:
The CS file of the view includes very little code, and its core logic is placed in the view model class, which reduces the program logic and the view coupling degree.
The ViewModel class acts as the DataContext of the view.
In MVVM, all events and actions are treated as commands, such as clicking on a button, not triggering a click event, but binding to a click command and then executing the corresponding logic by the command.

namespace wpfapplication1{    // First step: Nature is the data part, that is, the implementation of the model layer. Here you define a person class, which contains 2 basic properties. public    class  personmodel    {        publicstring   Getset;}          Public int Get Set ; }    }}
namespacewpfapplication1{//for testing purposes, a static method is created below to obtain the test data.      Public classPersondatahelper { Public StaticObservablecollection<personmodel>getpersons () {ObservableCollection<PersonModel> samplepersons =NewObservablecollection<personmodel>(); Samplepersons.add (NewPersonmodel () {Name ="Zhang San", age = - }); Samplepersons.add (NewPersonmodel () {Name ="Harry", age = A }); Samplepersons.add (NewPersonmodel () {Name ="John Doe", age = * }); Samplepersons.add (NewPersonmodel () {Name ="Learninghard", age = - }); returnsamplepersons; }    }}
namespacewpfapplication1{//The second step: Implement the ViewModel layer, realize the logic between the data and the interface. In the View model class, the properties and commands are included.//because in MVVM, events are handled as commands, where commands can only be bound to controls that have command properties. //now that you want to include a command, you first need to implement a command, where the custom command needs to implement the ICommand interface. //Here we define a querycommand. The specific implementation code is as follows:     Public classQuerycommand:icommand {#regionFieldsPrivateAction _execute; Privatefunc<BOOL>_canexecute; #endregion         PublicQuerycommand (Action execute): This(Execute,NULL)        {        }         PublicQuerycommand (Action Execute, func<BOOL>CanExecute) {            if(Execute = =NULL)                Throw NewArgumentNullException ("Execute"); _execute=Execute; _canexecute=CanExecute; }        #regionICommand Member Public EventEventHandler canexecutechanged {add {if(_canexecute! =NULL) {commandmanager.requerysuggested+=value; }} remove {if(_canexecute! =NULL) {commandmanager.requerysuggested-=value; }            }        }         Public BOOLCanExecute (Objectparameter) {            return_canexecute = =NULL?true: _canexecute (); }         Public voidExecute (Objectparameter)        {_execute (); }        #endregion    }}
     Public classpersonlistviewmodel:inotifypropertychanged {#regionFieldsPrivate string_searchtext; PrivateObservablecollection<personmodel>_resultlist; #endregion        #regionProperties PublicObservablecollection<personmodel> Personlist {Get;Private Set; } //Query Keywords         Public stringSearchText {Get{return_searchtext;} Set{_searchtext=value; raisePropertyChanged ("SearchText"); }        }        //Query Results         PublicObservablecollection<personmodel>Resultlist {Get{return_resultlist;} Set{_resultlist=value; raisePropertyChanged ("resultlist"); }        }         PublicICommand Querycommand {Get{return NewQuerycommand (searching, cansearching);} }        #endregion        #regionConstruction PublicPersonlistviewmodel () {personlist=persondatahelper.getpersons (); _resultlist=personlist; }        #endregion        #regionCommand Handler Public voidsearching () {ObservableCollection<PersonModel> personlist =NULL; if(string. Isnullorwhitespace (SearchText)) {resultlist=personlist; }            Else{personlist=NewObservablecollection<personmodel>(); foreach(Personmodel Pinchpersonlist) {                    if(P.name.contains (SearchText)) {Personlist.add (P); }                }                if(Personlist! =NULL) {resultlist=personlist; }            }        }         Public BOOLcansearching () {return true; }        #endregion        #regionINotifyPropertyChanged Members Public EventPropertyChangedEventHandler propertychanged; #endregion        #regionMethodsPrivate voidraisePropertyChanged (stringPropertyName) {            //Take a copy to prevent thread issuesPropertyChangedEventHandler handler =propertychanged; if(Handler! =NULL) {Handler ( This,NewPropertyChangedEventArgs (PropertyName)); }        }        #endregion    }
<Windowx:class= "Wpfapplication1.personsview"xmlns= "Http://schemas.microsoft.com/winfx/2006/xaml/presentation"xmlns:x= "Http://schemas.microsoft.com/winfx/2006/xaml"xmlns:local= "Clr-namespace:wpfapplication1"Title= "Personsview"Height= "+"Width= "+">    <Window.datacontext>        <Local:personlistviewmodel/>    </Window.datacontext>    <Grid>        <grid.rowdefinitions>            <RowDefinitionHeight= " the"/>            <RowDefinitionHeight="*"/>        </grid.rowdefinitions>        <TextBoxGrid.Row= "0"Name= "Searchtxt"Text="{Binding path=searchtext, mode=twoway}"HorizontalAlignment= "Left"Height= "+"Width= "280"Margin= "10,0,0,0"></TextBox>        <ButtonGrid.Row= "0"Name= "Searchbtn"Content= "Search"Command="{Binding Path=querycommand}"Width= "a"Height= "+"HorizontalAlignment= "Right"Margin= "0,0,10,0"></Button>        <DataGridGrid.Row= "1"Name= "Datgrid"HorizontalAlignment= "Center"VerticalAlignment= "Top"ItemsSource="{Binding Path=resultlist}"Width= "+"></DataGrid>    </Grid></Window>

WPF framework MVVM Simple Example

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.