`
cloudtech
  • 浏览: 4711054 次
  • 性别: Icon_minigender_1
  • 来自: 武汉
文章分类
社区版块
存档分类
最新评论

Silverlight MVVM模式开发 -MVVMLight

 
阅读更多

silverlight的mvvm模式框架有,MVVM Light:http://mvvmlight.codeplex.com

Caliburn:http://caliburn.codeplex.com/

Prism:http://compositewpf.codeplex.com/

其中MVVMLight是一个轻量级框架,大家可以参考。下面重点说一下View与Command的原理及使用。

大家可以参照源代码:

1.每一个ViewModel都继承ViewModelBase类:大致的源代码是:

using System;
using System.ComponentModel;
using System.Linq.Expressions;

namespace TAMS.Common
{
    /// <summary>
    /// INotifyPropertyChanged的基类
    /// </summary>
    public class PropertyChangedBase : INotifyPropertyChanged
    {
        public event PropertyChangedEventHandler PropertyChanged;

        public void NotifyPropertyChanged(string propertyName)
        {
            if (this.PropertyChanged != null)
            {
                this.PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
            }
        }
    }

    /// <summary>
    /// PropertyChangedBase的扩展方法
    /// </summary>
    public static class PropertyChangedBaseEx
    {
        public static void NotifyPropertyChanged<T, TProperty>(this T propertyChangedBase, Expression<Func<T, TProperty>> expression) where T : PropertyChangedBase
        {
            var memberExpression = expression.Body as MemberExpression;
            if (memberExpression != null)
            {
                string propertyName = memberExpression.Member.Name;
                propertyChangedBase.NotifyPropertyChanged(propertyName);
            }
            else
                throw new NotImplementedException();
        }
    }
}

2. Command类的核心:

using System;
using System.Windows.Input;

namespace TAMS.Common
{
    /// <summary>        
    /// 功能描述:Silverlight 命令 代理类
    /// 创 建 者:kntao
    /// 创建日期:2011/6/29
    /// 修改记录:            
    /// </summary>
    public class DelegateCommand : ICommand
    {
        /// <summary>
        /// Occurs when changes occur that affect whether the command should execute.
        /// </summary>
        public event EventHandler CanExecuteChanged;

        Func<object, bool> canExecute;
        Action<object> executeAction;
        bool canExecuteCache;

        /// <summary>
        /// Initializes a new instance of the <see cref="DelegateCommand"/> class.
        /// </summary>
        /// <param name="executeAction">The execute action.</param>
        /// <param name="canExecute">The can execute.</param>
        public DelegateCommand(Action<object> executeAction,Func<object, bool> canExecute)
        {
            this.executeAction = executeAction;
            this.canExecute = canExecute;
        }

        #region ICommand Members
        /// <summary>
        /// Defines the method that determines whether the command 
        /// can execute in its current state.
        /// </summary>
        /// <param name="parameter">
        /// Data used by the command. 
        /// If the command does not require data to be passed,
        /// this object can be set to null.
        /// </param>
        /// <returns>
        /// true if this command can be executed; otherwise, false.
        /// </returns>
        public bool CanExecute(object parameter)
        {
            bool tempCanExecute = canExecute(parameter);

            if (canExecuteCache != tempCanExecute)
            {
                canExecuteCache = tempCanExecute;
                if (CanExecuteChanged != null)
                {
                    CanExecuteChanged(this, new EventArgs());
                }
            }

            return canExecuteCache;
        }

        /// <summary>
        /// Defines the method to be called when the command is invoked.
        /// </summary>
        /// <param name="parameter">
        /// Data used by the command. 
        /// If the command does not require data to be passed, 
        /// this object can be set to null.
        /// </param>
        public void Execute(object parameter)
        {
            executeAction(parameter);
        }
        #endregion
    }
}
3. 一个简单的运用:显示图书的列表,并可以通过图书内容进行搜索:

XAML文件:

<UserControl
             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:sdk="http://schemas.microsoft.com/winfx/2006/xaml/presentation/sdk" x:Class="MvvmLight1.MainPage"
             mc:Ignorable="d"
             Height="800"
             Width="1024"
             >

    <UserControl.Resources>
        <ResourceDictionary>
            <ResourceDictionary.MergedDictionaries>
                <ResourceDictionary Source="Skins/MainSkin.xaml" />
            </ResourceDictionary.MergedDictionaries>
        </ResourceDictionary>
    </UserControl.Resources>

	<UserControl.DataContext>
		<Binding Path="Main" Source="{StaticResource Locator}"/>
	</UserControl.DataContext>

    <Grid x:Name="LayoutRoot">

        <TextBlock FontSize="36"
                   FontWeight="Bold"
                   Foreground="Purple"
                   Text="{Binding Welcome}"
                   VerticalAlignment="Center"
                   HorizontalAlignment="Center"
                   TextWrapping="Wrap" />
        <TextBox x:Name="textBox" HorizontalAlignment="Left" Margin="32,24,0,0" TextWrapping="Wrap" Text="" VerticalAlignment="Top" Width="201" />
        <Button Content="搜索" Margin="0,24,645,0" VerticalAlignment="Top" HorizontalAlignment="Right" Width="83" Command="{Binding SearchCommand, Mode=OneWay}" CommandParameter="{Binding Text, ElementName=textBox}" />

        <sdk:DataGrid  Margin="32,72,168,328" AutoGenerateColumns="False" ItemsSource="{Binding BookSource}" Height="400">
    		<sdk:DataGrid.Columns>
                <sdk:DataGridTextColumn Binding="{Binding BookIdBookId}" Header="图书编号"/>
                <sdk:DataGridTextColumn Binding="{Binding BookName}" Header="图书名称"/>
                <sdk:DataGridTextColumn Binding="{Binding BookAuthor}" Header="图书作者"/>
    		</sdk:DataGrid.Columns>
    	</sdk:DataGrid>

    </Grid>
</UserControl>
大家可以通过Blend界面设置绑定属性,


2. ViewModel

using System.Collections.Generic;
using GalaSoft.MvvmLight;
using System.Windows.Input;
using GalaSoft.MvvmLight.Command;
using System.Linq;

namespace MvvmLight1.ViewModel
{
    /// <summary>
    /// This class contains properties that the main View can data bind to.
    /// <para>
    /// Use the <strong>mvvminpc</strong> snippet to add bindable properties to this ViewModel.
    /// </para>
    /// <para>
    /// You can also use Blend to data bind with the tool's support.
    /// </para>
    /// <para>
    /// See http://www.galasoft.ch/mvvm/getstarted
    /// </para>
    /// </summary>
    public class MainViewModel : ViewModelBase
    {
        private IList<BookInfo> _bookSource;

        #region 绑定属性

        public IList<BookInfo> BookSource
        {
            get { return _bookSource; }
            set
            {
                if(_bookSource != value)
                {
                    _bookSource = value;
                    RaisePropertyChanged("BookSource");
                }
            }
        }

        #endregion
        /// <summary>
        /// Initializes a new instance of the MainViewModel class.
        /// </summary>
        public MainViewModel()
        {
            if (IsInDesignMode)
            {
                // Code runs in Blend --> create design time data.
            }
            else
            {
                // Code runs "for real"
                BookSource = GetBooks();
                SearchCommand = new RelayCommand<string>(
                    (bookTitle) =>
                        {
                            BookSource = GetBooks().Where(b => b.BookName.Contains(bookTitle)).ToList<BookInfo>();
                        }
                    );
            }
        }

        ////public override void Cleanup()
        ////{
        ////    // Clean up if needed

        ////    base.Cleanup();
        ////}

	
		#region Commands

        public ICommand SearchCommand { get; private set; }
			
		#endregion

        #region Data Source

        public class BookInfo
        {
            public int BookId { get; set; }
            public string BookName { get; set; }
            public string BookAuthor { get; set; }
        }


        public IList<BookInfo> GetBooks()
        {
            return new List<BookInfo>
                       {
                           new BookInfo() {BookId = 1, BookName = "CLR via C#(第3版)微软技术丛书", BookAuthor = "Richter"},
                           new BookInfo() {BookId = 2, BookName = "Windows Phone Mango开发实践", BookAuthor = "高雪松"},
                           new BookInfo() {BookId = 3, BookName = "C#本质论(第3版)", BookAuthor = "米凯利斯"},
                           new BookInfo() {BookId = 4, BookName = "ASP.NET本质论", BookAuthor = "郝冠军"},
                           new BookInfo() {BookId = 5, BookName = "Microsoft .NET企业级应用架构设计", BookAuthor = "埃斯波西托"},
                           new BookInfo() {BookId = 6, BookName = "你必须知道的.NET(第2版)", BookAuthor = "王涛"},
                           new BookInfo() {BookId = 7, BookName = "ASP.NET 4从入门到精通(微软技术丛书)", BookAuthor = "谢菲尔徳"},
                           new BookInfo() {BookId = 8, BookName = "ADO.NET 2.0技术内幕", BookAuthor = "斯塞帕(Sceppa,D.)"},
                           new BookInfo() {BookId = 9, BookName = "NET组件程序设计(第2版)", BookAuthor = "洛威(Lowy,J.)"},
                           new BookInfo(){BookId = 9, BookName = "庖丁解牛:纵向切入ASP.NET 3.5控件和组件开发技术(第2版)", BookAuthor = "郑健"}
                       };
        }
        #endregion
    }
}

代码下载:http://download.csdn.net/download/kntao/3730030


分享到:
评论

相关推荐

    MvvMLight2013-2015

    MvvMLight,全称为"Model-View-ViewModel Light",是由Laurent Bugnion创建的一个轻量级MVVM(Model-View-ViewModel)框架,专为简化WPF、Silverlight、Windows Phone以及Universal Windows Platform(UWP)应用程序...

    silverlight MVVM模式示例

    在Silverlight中,有一些库如Caliburn.Micro、Prism和MVVM Light等,它们提供了对MVVM模式的良好支持,包括依赖注入、事件代理、路由和导航等功能,帮助开发者更方便地实现MVVM架构。 综上所述,"Silverlight MVVM...

    Silverlight Mvvm light toolkit安装指南包括安装包及Demo

    Silverlight Mvvm light toolkit安装指南包括安装包及Demo 包含以下文件: GalaSoft.MvvmLight.V3SP1.zip MvvmLightDemo.rar Silverlight Mvvm light toolkit安装指南.docx

    MvvmLight-NuGet

    **MvvmLight-NuGet** 是一个专门为开发者提供的NuGet包,它包含了MvvmLight Toolkit的集成,使得在.NET框架下开发WPF、Silverlight、Windows Phone和Universal Windows Platform(UWP)应用时,能够更加方便地应用...

    wpf闹钟、设计模式、Mvvm模式、Mvvmlight

    MvvmLight是GalaSoft公司开发的一个轻量级的Mvvm库,它为WPF和Silverlight等平台提供了实现Mvvm模式的工具集。Mvvmlight包括了如DataContextProxy、EventToCommand、Messenger等实用组件,简化了ViewModel与View之间...

    Silverlight MVVMLight轻量级框架 官方实例(BUG收集系统)

    总的来说,"Silverlight MVVMLight轻量级框架 官方实例(BUG收集系统)"提供了一个实践MVVMLight的宝贵资源,对于想要提升Silverlight应用开发技能或者深入理解MVVM模式的开发者来说,这是一个非常有价值的学习案例...

    WPF-MvvmLight

    MvvmLight,全称Model-View-ViewModel Light,是由GalaSoft开发的一个轻量级的MVVM(Model-View-ViewModel)设计模式实现,它简化了WPF和Silverlight应用程序的开发过程。 MVVM设计模式是一种用于UI开发的架构模式...

    MVVM模式下的silverLight基于MySQL数据库的实例解析

    在SilverLight应用程序开发中,MVVM(Model-View-ViewModel)是一种常见的开发模式,它是MVC模式的一种变种。MVVM 模式将整个应用程序分为三个模块,即 Model、View 和 ViewModel。Model 负责存放实际数据和业务逻辑...

    各种版本的Galasoft.MvvmLight

    Galasoft.MvvmLight 是一个广泛使用的MVVM(Model-View-ViewModel)设计模式的轻量级框架,由Laurent Bugnion开发,旨在简化WPF、Silverlight、Windows Phone、Windows Store、Xamarin等平台的开发工作。在本文中,...

    MVVMLight.zip

    **MVVM Light 框架详解** MVVM Light 是一个流行的、轻量级的...总之,MVVMLight 是一个强大的工具,为WPF开发者提供了实现MVVM模式的便捷途径。通过熟练掌握其核心组件和工作原理,可以显著提升开发效率和软件质量。

    Silverlight MVVM

    在实践中,为了简化MVVM模式的使用,有许多第三方框架可供选择,如MVVM Light、Caliburn.Micro和Prism等。这些框架提供了便利的功能,如命令实现、数据绑定增强和依赖注入。 在MVVM_DEMO项目中,你可以看到一个...

    MvvmLight 简单demo

    MvvmLight(Model-View-ViewModel Light)是由法国开发者Laurent Bugnion创建的一个轻量级MVVM(Model-View-ViewModel)框架,适用于WPF、Silverlight、Windows Phone、Universal Windows Platform (UWP)以及Xamarin...

    MVVMLight框架下的wpf登陆程序demo

    2. ** GalaSoft.MvvmLight.Extras:** 扩展库,提供了一些额外的功能,如INavigationService导航服务,适用于WPF和Silverlight。 3. ** GalaSoft.MvvmLight.Threading:** 提供了DispatcherHelper类,用于在非UI线程...

    MVVMLight框架使用实例

    MVVMLight,全称为Model-View-ViewModel Light,是由Laurent Bugnion开发的一个轻量级的MVVM(Model-View-ViewModel)框架,广泛应用于WPF、Silverlight、Windows Phone以及UWP等平台。本实例将通过一个登录功能的...

    MVVM light小实例

    通过这个 MVVMLight Silverlight 小实例,我们了解了如何利用 MVVMLight 框架创建一个简单的应用程序。这个框架提供了强大的功能,包括命令绑定、依赖注入、事件代理等,使得开发过程更加高效。在实际项目中,可以...

    一个简单的MVVMLight显示图书列表的例子

    MVVMLight是一个轻量级的MVVM(Model-View-ViewModel)框架,由GalaSoft公司开发,适用于WPF、Silverlight、Windows Phone以及Universal Windows Platform等平台。在这个"一个简单的MVVMLight显示图书列表的例子"中...

    MEF 结合 MVVMLight

    **MEF(Managed Extensibility Framework)与MVVMLight结合使用是现代Windows应用程序开发中的一个常见实践,尤其在WPF和Silverlight项目中。MEF是一个用于构建可扩展应用程序的.NET框架,而MVVMLight则是一个轻量级...

    Silverlight开发MVVM框架(MVVM Light Toolkit) v4 beta1.rar

    GalaSoft.MvvmLight 类库 ViewModelBase 类是ViewModels的基础类,在开发中ViewModls类都要继承自它。 Messenger类 用于应用程序的通信。接收者仅接受注册过的消息类型。 此外,目标类型可以被指定,用Send,TTarget...

    WPF MvvMLight使用示例

    MvvmLight是Mvvm(Model-View-ViewModel)模式的一个轻量级库,由GalaSoft开发,旨在简化WPF、Silverlight和UWP应用中的MVVM设计模式实现。MvvmLight为开发者提供了诸如 Messenger、SimpleIoc、 GalaSoft....

    实现mvvm模式 Silverlight

    在实际项目中,我们可能还需要使用一些辅助工具和框架,如MVVMLight、Caliburn.Micro或Prism,它们提供了额外的基础设施支持,如事件代理、导航服务和自动注入ViewModel等,以简化MVVM模式的实现。 总之,MVVM模式...

Global site tag (gtag.js) - Google Analytics