WPF学习系列 MVVM设计模式 一

来源:互联网 发布:麒麟臂数据 编辑:程序博客网 时间:2024/06/06 16:41

从今天开始,就通过实例一步步的去熟悉,了解,应用MVVM设计模式。那么先看一下MVVM的项目分层。
 在项目中创建了3个文件夹,分别是Model,View,ViewModel  。最终形成了 M-V-VM设计模式一个标准化的分层。
 Model层顾名思义“模型”,首先我们在Model层中添加Student.cs类型类。
 public class Student
    {
       public int StudentID { get; set; }
       public string StudentName { get; set; }
       public double StudentScore { get; set; }
    }
然后在Students中得到一个泛型为Student的集合。
 public class Students
    {
       public List<Student> student;
       public List<Student> SetStudent()
       {
           student = new List<Student>()
           {
               new Student{StudentID = 1,StudentName="A",StudentScore = 90.5},
               new Student{StudentID = 2,StudentName="B",StudentScore = 98.6},
               new Student{StudentID = 3,StudentName="C",StudentScore = 83.2},
               new Student{StudentID = 4,StudentName="D",StudentScore = 71.5},
           };
           return student;
       }
    }
这样一个简单的数据模型就完成了。
接下来完成VIewModel,在ViewModel中获取到了Model中的集合,当然在ViewModel中还可以做更多的操作。
 public List<Student> AllStudents { get; set; }
       public StudentVM()
       {
           AllStudents = new Students().SetStudent();
       }
然后完成View层,在View层中添加一个用户控件StudenView.xaml。在View中实现了和ViewModel的绑定ItemsSource="{Binding Path=AllStudents}"
   <Grid Background="Orange">
        <DataGrid x:Name="dgView" Background="Transparent"  AutoGenerateColumns="False" ItemsSource="{Binding Path=AllStudents}">
            <DataGrid.Columns>
                <DataGridTextColumn Width="50" Header="编号" Binding="{Binding Path=StudentID}" IsReadOnly="True"></DataGridTextColumn>
                <DataGridTextColumn Width="50" Header="姓名" Binding="{Binding Path=StudentName}" IsReadOnly="True"></DataGridTextColumn>
                <DataGridTextColumn Width="50" Header="分数" Binding="{Binding Path=StudentScore}" IsReadOnly="True"></DataGridTextColumn>
            </DataGrid.Columns>
        </DataGrid>
    </Grid>
最后将View添加到 MainWindow.xaml上面
<Window x:Class="MVVMTest.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:view="clr-namespace:MVVMTest.View"
        xmlns:viewmodel="clr-namespace:MVVMTest.ViewModel"
        Title="MVVM实战一" Height="500" Width="500" WindowStartupLocation="CenterScreen">
    <Window.Resources>
        <viewmodel:StudentVM  x:Key="vm"></viewmodel:StudentVM>
    </Window.Resources>
     <Grid DataContext="{StaticResource vm}">
        <view:StudentView Margin="50,50"></view:StudentView>
    </Grid>
</Window>
这样第一个简单的MVVM实例就完成了!
原创粉丝点击