WPF Quick Start series (8) -- MVVM Quick Start, wpfmvvm

Source: Internet
Author: User

WPF Quick Start series (8) -- MVVM Quick Start, wpfmvvm
I. Introduction

This section describes some of the core content of WPF, including the WPF layout, dependency attributes, routing events, binding, commands, resource styles, and templates. However, a good programming framework (WVVM) has also been developed in WPF. MVC has been developed on the Web Side and MVVM has been developed on the WPF client, among them, VM is equivalent to C (Control) in MVC ). On the Web side, Microsoft developed an MVC framework such as Asp.net MVC. In the WPF field, Microsoft also developed an MVVM framework such as Prism. The Prism Project address is http://compositewpf.codeplex.com/sourcecontrol/latest. If you are interested, download the source code.

Download all source code in this article: frightvvmproject.zip II. What is the MVVM mode?

Now that we talk about the MVVM model, the first question is the meaning of MVVM. MVVM is short for Model-View-ViewModel. It is usually used for WPF or Silverlight development. The relationship between the three is shown in:

Model)

Model -- can be understood as a class with fields and attributes.

View)

View -- it can be understood as the UI we see.

View Model)

The View Model connects the View and Model, and separates the View and Model layers. View Model is not only a Model package, but also contains Program Logic and Model extensions. For example, if a public attribute in the Model does not need to be displayed on the UI, in this case, we can no longer define it in the View Model.

In MVVM mode, the running process of the WPF program is shown in:

Public class Person {public string Name {get; set;} public int Age {get; set ;}}

To perform the test, create a static method to obtain the test data.

Public class PersonDataHelper {public static ObservableCollection <Person> GetPersons () {ObservableCollection <Person> samplePersons = new ObservableCollection <Person> (); samplePersons. add (new Person () {Name = "James", Age = 33}); samplePersons. add (new Person () {Name = "", Age = 22}); samplePersons. add (new Person () {Name = "", Age = 35}); samplePersons. add (new Person () {Name = "LearningHard", Age = 27}); return samplePersons ;}}

  Step 2: implement the ViewModel layer and implement the logic between the data and the interface.The view model class contains attributes and commands. In MVVM, events are processed as commands. commands can only be bound to controls with Command attributes. To include commands, you must first implement a command. Here, the custom commands must implement the ICommand interface. Here we define a QueryCommand. The specific implementation code is as follows:

public class QueryCommand :ICommand    {        #region Fields        private Action _execute;        private Func<bool> _canExecute;        #endregion         public QueryCommand(Action execute)            : this(execute, null)        {         }        public QueryCommand(Action execute, Func<bool> canExecute)        {            if (execute == null)                throw new ArgumentNullException("execute");            _execute = execute;            _canExecute = canExecute;        }        #region ICommand Member        public event EventHandler CanExecuteChanged        {            add            {                if (_canExecute != null)                {                    CommandManager.RequerySuggested += value;                }            }            remove            {                if (_canExecute != null)                {                    CommandManager.RequerySuggested -= value;                }            }        }        public bool CanExecute(object parameter)        {            return _canExecute == null ? true : _canExecute();        }        public void Execute(object parameter)        {            _execute();        }        #endregion    }

Next we will define our ViewModel class. The specific implementation code is as follows:

1 public class PersonListViewModel: INotifyPropertyChanged 2 {3 # region Fields 4 private string _ searchText; 5 private ObservableCollection <Person> _ resultList; 6 # endregion 7 8 # region Properties 9 10 public ObservableCollection <Person> PersonList {get; private set ;} 11 12 // query keyword 13 public string SearchText14 {15 get {return _ searchText;} 16 set17 {18 _ searchText = value; 19 RaisePropertyChang Ed ("SearchText"); 20} 21} 22 23 // query result 24 public ObservableCollection <Person> ResultList25 {26 get {return _ resultList ;} 27 set28 {29 _ resultList = value; 30 RaisePropertyChanged ("ResultList"); 31} 32} 33 34 public ICommand QueryCommand 35 {36 get {return new QueryCommand (Searching, canSearching);} 37} 38 39 # endregion 40 41 # region Construction42 public PersonListViewModel () 43 {44 PersonList = P ErsonDataHelper. getPersons (); 45 _ resultList = PersonList; 46} 47 48 # endregion49 50 # region Command Handler51 public void Searching () 52 {53 ObservableCollection <Person> personList = null; 54 if (string. isNullOrWhiteSpace (SearchText) 55 {56 ResultList = PersonList; 57} 58 else59 {60 personList = new ObservableCollection <Person> (); 61 foreach (Person p in PersonList) 62 {63 if (p. name. contains (SearchText) 64 {65 personList. Add (p); 66} 67} 68 if (personList! = Null) 69 {70 ResultList = personList; 71} 72} 73} 74 75 public bool CanSearching () 76 {77 return true; 78} 79 80 # endregion 81 82 # region INotifyPropertyChanged Members83 84 public event PropertyChangedEventHandler PropertyChanged; 85 86 # endregion87 88 # region Methods89 private void RaisePropertyChanged (string propertyName) 90 {91 // take a copy to prevent thread issues92 PropertyChangedEventHandler h Andler = PropertyChanged; 93 if (handler! = Null) 94 {95 handler (this, new PropertyChangedEventArgs (propertyName); 96} 97} 98 # endregion 99}

  Step 3: implement the View layer, design our View, and set its DataContext attribute to the ViewModel class.. The specific XAML code is as follows:

<Window x: Class = "MVVMDemo. View. PersonsView" xmlns =" http://schemas.microsoft.com/winfx/2006/xaml /Presentation "xmlns: x =" http://schemas.microsoft.com/winfx/2006/xaml "Xmlns: local =" clr-namespace: MVVMDemo. ViewModel "Title =" PersonsView "Height =" 350 "Width =" 400 "> <! -- Set DataContex to the ViewModel class. Of course, you can also use the background code to set --> <Window. dataContext> <local: PersonListViewModel/> </Window. dataContext> <Grid. rowDefinitions> <RowDefinition Height = "50"/> <RowDefinition Height = "*"/> </Grid. rowDefinitions> <TextBox Grid. row = "0" Name = "searchtxt" Text = "{Binding Path = SearchText, mode = TwoWay} "HorizontalAlignment =" Left "Height =" 30 "Width =" 280 "Margin =", 0, "> </TextBox> <Button Grid. row = "0" Name = "searchBtn" Content = "Search" Command = "{Binding Path = QueryCommand}" Width = "80" Height = "30" HorizontalAlignment = "Right" margin = "0, 0, 10, 0 "> </Button> <DataGrid Grid. row = "1" Name = "datGrid" HorizontalAlignment = "Center" verticalignment = "Top" ItemsSource = "{Binding Path = ResultList}" Width = "300"> </DataGrid> </Grid> </Window>

At this point, our mvvm wpf program has been completed. The following is to see if the program has achieved our intended purpose. The specific running result is shown in:

Iv. Summary

At this point, the content of this article has been shared, and this article is also the last article of the WPF series. I hope this series will allow beginners to quickly get started with WPF programming. In the following time, I plan to write some practical content, because I used to share some of the beginner's series, and then I plan to share some practical project implementations, and the content of the field-driven design, hoping to be promoted and supported by everyone.

 

 

 

Related Article

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.