上一篇文章写得查询比较简单,这次做一个基于MVVM下的增删改。只要按照步骤来,没有不会的。

第一步:创建一个silverlight项目;

第二步:添加项目对 GalaSoft.MvvmLight.Extras.SL4,GalaSoft.MvvmLight.SL4, System.Windows.Controls.Data, Microsoft.Practices.Unity.Silverlight的引用

第三步:创建相应的文件夹ViewModelModel View

第四步:在Model文件夹下新建一个类Student.cs类,代码如下:

    public class Student

    {

        public string Name { get; set; }//名字

        public int Age { get; set; } //年龄

        public int SNo { get; set; }//学号

}

第五步:还是在Model文件夹下新建一个类Students.cs ,这个类的作用是用于构造数据。

    private ObservableCollection<Student> _getstudents;

    public ObservableCollection<Student> GetStudent()

    {

        _getstudents = new ObservableCollection<Student>(){

           new Student{ Name="张三", Age=21, SNo=11},

           new Student{ Name="李四", Age=22, SNo=12},

         new Student{ Name="王五", Age=23, SNo=13},

       new Student{ Name="高尚", Age=24, SNo=14},

        };

        return _getstudents;

}

第六步:在ViewModel下创建StudentViewModel.cs类,这个类主要是连接modelview

第七步:从这开始就是怎么把ViewModel里的数据输送到前台的。

首先在ViewModel里创建ViewModelLocator.cs我们叫它ViewModel加载器

里面的代码如下:

using GalaSoft.MvvmLight;
using Microsoft.Practices.Unity; //需要引入Microsoft.Practices.Unity.Silverlight 命名空间

  public class ViewModelLocator
    {

        public static IUnityContainer Container
        {
            get;
            private set;
        }

        //创建一个容器,把StudentViewModel 扔到这个容器里,前台只需要在这个容器里取值就行了。
        static ViewModelLocator()
        {
            Container = new UnityContainer();

            Container.RegisterType<StudentViewModel>(new ContainerControlledLifetimeManager());
        }

        /// <summary>
        /// 首页操作
        /// </summary>
        public StudentViewModel MyStu
        {
            get
            {
                return Container.Resolve<StudentViewModel>();
            }
        }

    }

第二步:在App.xaml 里添加代码,引用ViewModelLocator.cs里的东东。

<?xml version="1.0" encoding="utf-8"?>

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

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

             xmlns:d="http://schemas.microsoft.com/expression/blend/2008" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"

     这个就是viewmodel那个文件夹

             xmlns:vm="clr-namespace:SilverlightApplication1.ViewModel"

mc:Ignorable="d">

 <!--全局 View Model 加载器--> 别名是Locator

  <Application.Resources>

    <vm:ViewModelLocator x:Key="Locator" d:IsDataSource="True" />

  </Application.Resources>

</Application>

第八步:前台处理

 这样一个简单的查询就做完了。注意这里,MainPage.xaml没有写一句代码

 

<UserControl x:Class="SilverlightApplication1.MainPage"

    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"

     引入的一些东西,有的具体是干嘛的,我也不太懂。    

需要引入System.Windows.Controls.Data命名空间   xmlns:data="clr-namespace:System.Windows.Controls;assembly=System.Windows.Controls.Data"  

         xmlns:i="http://schemas.microsoft.com/expression/2010/interactivity"

xmlns:GalaSoft_MvvmLight_Command="clr-namespace:GalaSoft.MvvmLight.Command;assembly=GalaSoft.MvvmLight.Extras.SL4"

   首先为页面设置DataContext为StudentViewModel,

注意观察这个 MyStu对应的是ViewModelLocator.cs里的类名 Source={StaticResource Locator} 还记得那个别名吗?呵呵,就是这个

   DataContext="{Binding MyStu, Mode=TwoWay, Source={StaticResource Locator}}"

    mc:Ignorable="d"

    d:DesignHeight="300" d:DesignWidth="400" >

全局调用MyStu对应类下面的RefreshCommand。就是StudentViewModel下的RefreshCommand ,进行查询

<i:Interaction.Triggers>

            <i:EventTrigger>

                <GalaSoft_MvvmLight_Command:EventToCommand Command="{Binding RefreshCommand, Mode=TwoWay}"/>

            </i:EventTrigger>

        </i:Interaction.Triggers>

 

        <Grid x:Name="LayoutRoot"  Background="White" Height="312" Width="442" >

    ItemsSource="{Binding Students, Mode=TwoWay}" 绑定数据源Students

        <data:DataGrid  Height="177"   AutoGenerateColumns="False"  HorizontalAlignment="Left" Margin="22,109,0,0"  Name="dataGrid1" VerticalAlignment="Top" Width="374" ItemsSource="{Binding Students, Mode=TwoWay}">

                <data:DataGrid.Columns>

                    <data:DataGridTextColumn Header="姓名" Width="70" Binding="{Binding Name, Mode=TwoWay}" d:IsLocked="True"/>

                    <data:DataGridTextColumn Header="年龄?" Width="70" Binding="{Binding Age, Mode=TwoWay}" d:IsLocked="True"/>

                    <data:DataGridTemplateColumn Header="删除" Width="80" d:IsLocked="True">

                        <data:DataGridTemplateColumn.CellTemplate>

                            <DataTemplate>

调用StudentViewModel下的DelCommand方法,实现删除。               

<Button  HorizontalAlignment="Center" VerticalAlignment="Center" Content="删除" Command="{Binding MyStu.DelCommand, Mode=OneWay, Source={StaticResource Locator}}" CommandParameter="{Binding Mode=OneWay}" ></Button>

                            </DataTemplate>

                        </data:DataGridTemplateColumn.CellTemplate>

                    </data:DataGridTemplateColumn>

                </data:DataGrid.Columns>

            </data:DataGrid>

    </Grid>

</UserControl>

 

 

 

第二讲:添加我们直接从第六步开始写,首先StudentViewModel

下写一个添加的方法。  AddCommand = new RelayCommand(() =>

            {

                Student stu = new Student();

                stu.Name = stuName;

                stu.Age = stuAge;

                stu.SNo = randmom.Next(1, 100);

                Students.Add(stu);

            });

这样,前台添加按钮绑定上AddCommand 就可以了。

前台

            <Button Content="添加¨®" Height="23" HorizontalAlignment="Right" Margin="0,53,59,0" Name="button1" VerticalAlignment="Top" Width="75"   Command="{Binding AddCommand, Mode=TwoWay}" />

StuName绑定的是对应的属性。不是model里的属性,是在StudentViewModel下创建的属性。

            <TextBox Height="23" HorizontalAlignment="Left" Margin="70,53,0,0" Name="txtName" VerticalAlignment="Top" Text="{Binding StuName, Mode=TwoWay}" Width="87" />

            <TextBox Height="23" HorizontalAlignment="Left" Margin="209,53,0,0" Name="txtAge" VerticalAlignment="Top" Text="{Binding StuAge, Mode=TwoWay}"  Width="83" />

第三讲:删除,会了前2个,估计删除也比较简单了。

应为删除按钮我放在的是DataGrid里面,

Command 下的属性是 MyStu.DelCommand 而添加直接是AddCommand,为什么呢?

应为删除是在DataGrid里面,里面已经绑定了数据源Students Students 没有DelCommand方法,所以需要到StudentViewModel去找。所以要用全局的MyStu去找DelCommand方法

 这里可能理解的不太懂,还请高手指教。

 <DataTemplate>

     <Button  HorizontalAlignment="Center" VerticalAlignment="Center" Content="删除" Command="{Binding MyStu.DelCommand, Mode=OneWay, Source={StaticResource Locator}}" CommandParameter="{Binding Mode=OneWay}" ></Button>

       </DataTemplate>

 做完上面练习,基本上也就会做了。

怎么分享源代码呢?不会呀。

作者: 高导 发表于 2011-07-27 14:45 原文链接

推荐.NET配套的通用数据层ORM框架:CYQ.Data 通用数据层框架
新浪微博粉丝精灵,刷粉丝、刷评论、刷转发、企业商家微博营销必备工具"