半岛权威十大直营(官方)网站

基于MVVM下的Silverlight之增删改

转帖|其它|编辑:郝浩|2011-07-29 14:55:58.000|阅读 674 次

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

# 界面/图表报表/文档/IDE等千款热门软控件火热销售中 >>

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

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

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

  第三步:创建相应的文件夹ViewModel和Model 和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类 ,这个类的作用是用于构造数据。

  &nbsp; private ObservableCollection<Student> _getstudents;

  &nbsp; public ObservableCollection<Student> GetStudent()

    {

     &nbsp;  _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},

        };

    &nbsp;   return _getstudents;

}

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

  第七步:从这开始就是怎么把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="//schemas.microsoft.com/winfx/2006/xaml/presentation"

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

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

     这个就是viewmodel那个文件夹

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

mc:Ignorable="d">

应用整个viewmodel里的东西。别名是Locator

  <Application.Resources>

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

  </Application.Resources>

</Application>

  第八步:前台处理

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

<;UserControl x:Class="SilverlightApplication1.MainPage"

    xmlns="//schemas.microsoft.com/winfx/2006/xaml/presentation&quot;

    xmlns:x="//schemas.microsoft.com/winfx/2006/xaml"

    xmlns:d="//schemas.microsoft.com/expression/blend/2008"

    xmlns:mc="//schemas.openxmlformats.org/markup-compatibility/2006"

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

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

  &nbsp;      xmlns:i="//schemas.microsoft.com/expression/2010/interactivity"

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

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

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

    mc:Ignorable="d"

    d:DesignHeight="300&quot; d:DesignWidth="400" >

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

<i:Interaction.Triggers>

            <i:EventTrigger>

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

            </i:EventTrigger>

 &nbsp;      </i:Interaction.Triggers>

 

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

    ItemsSource="{Binding Students, Mode=TwoWay}&quot; 绑定数据源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}">

              &nbsp; <data:DataGrid.Columns>

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

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

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

  &nbsp;                     <data:DataGridTemplateColumn.CellTemplate>

         ;  ;                 <DataTemplate>

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

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

                            </DataTemplate>

       ;              &nbsp;  </data:DataGridTemplateColumn.CellTemplate>

               ;     </data:DataGridTemplateColumn>

            &nbsp;   </data:DataGrid.Columns>

            </data:DataGrid>

    </Grid>

</UserControl>

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

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

&nbsp;           {

                Student stu = new Student();

                stu.Name = stuName;

             &nbsp;  stu.Age = stuAge;

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

&nbsp;               Students.Add(stu);

        &nbsp;   });

  这样,前台添加按钮绑定上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" />

&nbsp;           <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>

   &nbsp;   </DataTemplate>

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


标签:MVVM

本站文章除注明转载外,均为本站原创或翻译。欢迎任何形式的转载,但请务必注明出处、不得修改原文相关链接,如果存在内容上的异议请邮件反馈至chenjj@wqylolg.cn

文章转载自:博客园

为你推荐

  • 推荐视频
  • 推荐活动
  • 推荐产品
  • 推荐文章
  • 慧都慧问
扫码咨询


添加微信 立即咨询

电话咨询

客服热线
023-68661681

TOP