无废话WPF系列19:MVVM简单介绍

MVVM主要是为了逻辑代码和视图的分离,使CodeBehind只包含对UI的操作。通过绑定和Command来实现

image

下面我们实现一个最简单的示例,点击按钮使年龄加1.

image

XAML代码

<Window x:Class="DeepXAML.MainWindow"

        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"

        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"

        xmlns:local="clr-namespace:DeepXAML"       

        xmlns:sys="clr-namespace:System;assembly=mscorlib"

         xmlns:cl="clr-namespace:System.Collections;assembly=mscorlib"

        Title="MainWindow" Height="250" Width="450">

       <StackPanel>

        <TextBox Text="{Binding Path=Name}"></TextBox>

        <TextBox Text="{Binding Path=Age}"></TextBox>

        <Button Command="{Binding Path=AddAge}" >Add Age</Button>

    </StackPanel>

</Window>

 

MainPageViewModel

 public class MainPageViewModel : INotifyPropertyChanged

    {

        public event PropertyChangedEventHandler PropertyChanged;



        private string name;

        public string Name {

            get { return name; }

            set {

                name = value;

                if (this.PropertyChanged != null)

                {

                    this.PropertyChanged.Invoke(this, new PropertyChangedEventArgs("Name"));

                }

            }

        }



        private int age;

        public int Age {

            get { return age; }

            set

            {

                age = value;

                if (this.PropertyChanged != null)

                {

                    this.PropertyChanged.Invoke(this, new PropertyChangedEventArgs("Age"));

                }

            }

        }



        public ICommand AddAge

        {

            get { return new AddAgeCommand(this); }

        }



    }

 

 public class AddAgeCommand : ICommand

    {

        private MainPageViewModel mMainPageViewModel;

        public AddAgeCommand(MainPageViewModel model)

        {

            mMainPageViewModel = model;

        }



        public bool CanExecute(object parameter)

        {

            return true;

           

        }



        public event EventHandler CanExecuteChanged;



        public void Execute(object parameter)

        {

            this.mMainPageViewModel.Age += 1;

        }

    }

 

我们可以看一下后台只有很少代码:

public partial class MainWindow : Window

    {

        public MainWindow()

        {

            InitializeComponent();

            MainPageViewModel mainPageViewModel = new MainPageViewModel { Age = 20, Name = "Jack" };

            this.DataContext = mainPageViewModel;

        }      

    }

你可能感兴趣的:(WPF)