今天学习wpf的mvvm
人家说,APS.NET ===>MVC
WPF===>MVVM
用WPF不用mvvm的话,不如用winform。。。
哈哈,题外话。
定义:
MVVM:
WPF的数据绑定与Presentation Model相结合是非常好的做法,使得开发人员可以将View和逻辑分离出来,但这种数据绑定技术非常简单实用,也是WPF所特有的,所以我们又称之为Model-View-ViewModel(MVVM)。这种模式跟经典的MVP(Model-View-Presenter)模式很相似,除了你需要一个为View量身定制的model,这个model就是ViewModel。ViewModel包含所有由UI特定的接口和属性,并由一个 ViewModel 的视图的绑定属性,并可获得二者之间的松散耦合,所以需要在ViewModel 直接更新视图中编写相应代码。数据绑定系统还支持提供了标准化的方式传输到视图的验证错误的输入的验证。
model,数据模型,
view,视图,界面
viewmodel,视图模型,用来连接view,和model的中间的东东。
public class Model { public string Name { get; set; } public int Age { get; set; } }
<Window x:Class="WpfApplication1.MainWindow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:d="http://schemas.microsoft.com/expression/blend/2008" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" xmlns:local="clr-namespace:WpfApplication1" mc:Ignorable="d" Title="MainWindow" Height="350" Width="525"> <Grid> <Grid.ColumnDefinitions> <ColumnDefinition></ColumnDefinition> <ColumnDefinition></ColumnDefinition> </Grid.ColumnDefinitions> <ListBox x:Name="listBox" ItemsSource="{Binding Models}" DisplayMemberPath="Name" SelectedItem="{Binding SelectedModel,Mode=TwoWay}"> </ListBox> <StackPanel Grid.Column="1" VerticalAlignment="Center"> <TextBlock Text="名字"></TextBlock> <TextBox Text="{Binding SelectedModel.Name}"></TextBox> <TextBlock Text="年龄"></TextBlock> <TextBox Text="{Binding SelectedModel.Age}"></TextBox> </StackPanel> </Grid> </Window>
public partial class MainWindow : Window { public MainWindow() { InitializeComponent(); this.DataContext = new ViewModel(); } }
public abstract class ViewModelBase : INotifyPropertyChanged { #region Property Changed Event Handler public void SetPropertyChanged(string propertyName) { if (PropertyChanged != null) PropertyChanged(this, new PropertyChangedEventArgs(propertyName)); } public event PropertyChangedEventHandler PropertyChanged; #endregion Property Changed Event Handler } public class ViewModel : ViewModelBase { public ObservableCollection<Model> Models { get; set; } private Model selectedModel; public Model SelectedModel { get { return selectedModel; } set { selectedModel = value; SetPropertyChanged("SelectedModel"); } } public ViewModel() { Models = GetData(); } public ObservableCollection<Model> GetData() { return GetDataFromDB(); } private ObservableCollection<Model> GetDataFromDB() { ObservableCollection<Model> result = new ObservableCollection<Model>(); for (int i = 0; i < 20; i++) { result.Add(new Model() { Name = "Name" + i, Age = i, }); } return result; } }
补充:
其实可以不用在界面的behindcode 赋值DataContext,直接在界面引用。
<Window.DataContext> <local:ViewModel/> </Window.DataContext>