To develop a WPF application, you have to mention MVVM. I'll show you a simple implementation of MVVM, mainly in the implementation of ICommand, but this implementation should not be used by many people in development, only for learning.
Get ready:
The interface is drawn in a simple box with a TextBox and button buttons.
Start
Next write ViewModel, note that ViewModel need to inherit the interface INotifyPropertyChanged, its main function is to ensure that the background property changes can notify the foreground changes.
Class Testviewmodel:inotifypropertychanged {private string teststr; <summary>///For notification string///</summary> public string Teststr {get {R} Eturn Teststr; } set {teststr = value; Raisechanged ("Teststr"); }}///<summary>///TEST command///</summary> public ICommand Testcommand {get ; Set Public Testviewmodel () {Testcommand = new Testcommand (this); } #region INotifyPropertyChanged interface implements public void Raisechanged (String propertyname) {if (P Ropertychanged! = null) {propertychanged (this, new PropertyChangedEventArgs (PropertyName)); }} public event PropertyChangedEventHandler propertychanged; #endregion}
In the code we see a Testcommand class used in Testviewmodel. This is the implementation of this class, which is mainly an implementation of ICommand "not recommended in development"
Class Testcommand:icommand {public Testcommand (Testviewmodel viemo) {viewmodel = Viemo; } Testviewmodel Viewmodel{get;set;} Public event EventHandler canexecutechanged {add {commandmanager.requerysuggested + = value;} Remove {commandmanager.requerysuggested-= value;} } int i = 0; <summary>///Command available///</summary>//<param name= "parameter" ></param> <returns></returns> public bool CanExecute (object parameter) {return true ; }///<summary>///command to perform the operation///</summary>//<param name= "parameter" ></ param> public void Execute (object parameter) {i++; ViewModel. Teststr = i.ToString (); } }
Finally, the ViewModel content is bound to the interface!
Xaml:
<window x:class= "WPF_MVVM. MainWindow " xmlns=" http://schemas.microsoft.com/winfx/2006/xaml/presentation " xmlns:x="/http/ Schemas.microsoft.com/winfx/2006/xaml " title=" MainWindow "height=" width= "525" > <Grid> <Grid.RowDefinitions> <rowdefinition height= "*"/> <rowdefinition height= "/> " </Grid.RowDefinitions> <textbox text= "{Binding teststr}"/> <button grid.row= "1" content= " Test "command=" {Binding testcommand} "/> </Grid></Window>
Codebehind:
public partial class Mainwindow:window {public MainWindow () { InitializeComponent (); This. DataContext = new Testviewmodel (); } }
Such a simple MVVM program is implemented. Oh, by the way, it's not a model, it's not a full mvvm, so leave it to yourself to think about it.
Project code managed Address: https://wpfmvvm.codeplex.com/
WPF's MVVM (STEP1)-implements ICommand interfaces on its own