且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

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

更新时间:2022-09-09 09:42:51

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

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

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

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

XAML代码

1
2
3
4
5
6
7
8
9
10
11
12
13
<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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
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); }
       }
 
   }

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
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;
       }
   }

 

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

1
2
3
4
5
6
7
8
9
public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
            MainPageViewModel mainPageViewModel = new MainPageViewModel { Age = 20, Name = "Jack" };
            this.DataContext = mainPageViewModel;
        }     
    }
本文转自敏捷的水博客园博客,原文链接http://www.cnblogs.com/cnblogsfans/archive/2011/03/01/1967858.html如需转载请自行联系原作者

王德水