无废话WPF系列19:MVVM简单介绍
2011-03-01 12:33 敏捷的水 阅读(1625) 评论(3) 编辑 收藏 举报MVVM主要是为了逻辑代码和视图的分离,使CodeBehind只包含对UI的操作。通过绑定和Command来实现
下面我们实现一个最简单的示例,点击按钮使年龄加1.
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; } }
扫码关注公众号,了解更多管理,见识,育儿等内容
![](https://www.cnblogs.com/images/cnblogs_com/cnblogsfans/172349/o_qrcode_for_gh_fe8f228bad0d_258.jpg)
作者: 王德水
出处:http://www.cnblogs.com/cnblogsfans
版权:本文版权归作者所有,转载需经作者同意。
出处:http://www.cnblogs.com/cnblogsfans
版权:本文版权归作者所有,转载需经作者同意。