关于MvvmLight框架的介绍可以看这篇,说的很详细,在此记录下来以作复习,通过一个简单的例子说明MvvmLight的基本使用

https://www.cnblogs.com/3xiaolonglong/p/10001787.html

首先MvvmLight框架最大的优点就是起到分离试图(View)和模型(Model)的作用,相对于之前把逻辑结构写在Code Behind 的方式,MVVM模式几乎完全解耦了视图和逻辑业务的关系,通过数据绑定和命令绑定来处理UI属性及事件驱动;同时,ViewModel中对属性的变更也会通知到View前端,让View前端实时更新。

MVVM中,各个部分的职责如下:

Model:负责数据实体的结构处理,与ViewModel进行交互;

View:负责界面显示,与ViewModel进行数据和命令的交互;

ViewModel:负责前端视图业务级别的逻辑结构组织,并将其反馈给前端。
 
按照大佬的步骤安装MVVMLight,然后新建一个MVVMLight框架的WPF项目,项目中包括ViewModel文件夹,里面有MainViewModel.cs和ViewModelLocator.cs两个文件。
下面我们就首先分析下这两个文件的内容:
MainViewModel.cs文件分析:
MainViewModel.cs文件中只有一个类MainViewModel,该类是主窗口MainWindow对应的ViewModel,继承自类ViewModelBase
ViewModelBase类又继承类ObservableObject,同时实现ICleanup接口
ObservableObject类实现INotifyPropertyChanged接口,用于通知属性的改变
由此分析,我们可以得出以下一般结论:
当我们定义一个自己的ViewModel时,一般让自定义ViewModel继承自ViewModelBase类,这样当ViewModel中属性发生变化的时候,就可以自动通知对应的VIew。
ViewModelLocator.cs文件分析:
ViewModelLocator.cs文件中只有一个ViewModelLocator类,类中包括一个构造函数、一个类型为MainViewModel的Main属性、以及一个静态的Cleanup函数。
下面这个例子把MainWindow和MainViewModel名称分别改为了LoadWindow和LoadViewModel了,其他都一样。
前台xmal主要代码如下,大家可以弄一个简单的界面测试就行:
 
 
在App.xmal中的代码:
<Application x:Class="MvvmLightDemo.App"
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:local="clr-namespace:MvvmLightDemo"
xmlns:System="clr-namespace:System;assembly=mscorlib"
xmlns:vm="clr-namespace:MvvmLightDemo.ViewModel"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" mc:Ignorable="d"
StartupUri="LoadWindow.xaml">
<!--控件的顶级资源-->
<Application.Resources>
<ResourceDictionary>
<vm:ViewModelLocator x:Key="Locator" />
</ResourceDictionary>
</Application.Resources>
</Application>
xmal.cs前端代码:
 
<Window x:Class="MvvmLightDemo.LoadWindow" 
        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:MvvmLightDemo"
        mc:Ignorable="d"
         FontFamily="Arial"
        FontSize="20"
        WindowStyle="None"
        Background="Transparent"
        WindowStartupLocation="CenterScreen"
        ResizeMode="NoResize"
        <!--通过该句获取LoadViewModel示例-->
        DataContext="{Binding Source={StaticResource Locator}, Path=LoadVM_Instance}"
        Title="LoadWindow" Height="550" Width="700">
    <Grid Margin="0">
        <Grid.RowDefinitions>
            <RowDefinition Height="Auto"></RowDefinition>
            <RowDefinition Height="1*"></RowDefinition>
            <RowDefinition Height="Auto"/>
        </Grid.RowDefinitions>
        <Grid Grid.Row="1" Opacity="0.9" Grid.RowSpan="2">
            <Border Grid.Column="1" Grid.Row="0" BorderBrush="DarkGray" BorderThickness="0 1 1 1" Panel.ZIndex="1">
                <Grid>
                    <Grid.RowDefinitions>
                        <RowDefinition Height="100"></RowDefinition>
                        <RowDefinition Height="1*"></RowDefinition>
                    </Grid.RowDefinitions>
                    <Grid Grid.Row="1">
                        <Grid.RowDefinitions>
                            <RowDefinition></RowDefinition>
                            <RowDefinition></RowDefinition>
                            <RowDefinition></RowDefinition>
                            <RowDefinition></RowDefinition>
                        </Grid.RowDefinitions>
                        <Grid.ColumnDefinitions>
                            <ColumnDefinition Width="Auto"></ColumnDefinition>
                            <ColumnDefinition Width="1*"></ColumnDefinition>
                            <ColumnDefinition Width="1*"></ColumnDefinition>
                        </Grid.ColumnDefinitions>
                        <TextBlock Grid.Row="0" Grid.Column="0" Text="User Id:" FontFamily="Arial" FontSize="18" Foreground="#99F8F8F8" HorizontalAlignment="Right" VerticalAlignment="Center"></TextBlock>
                        <TextBlock Grid.Row="1" Grid.Column="0"  Text="PassWord:" FontFamily="Arial" FontSize="18" Foreground="#99F8F8F8" HorizontalAlignment="Right" VerticalAlignment="Center"></TextBlock>
                        <TextBox Text="" x:Name="txtUserId" Grid.Row="0" Grid.Column="1" Grid.ColumnSpan="2" Margin="6 8 10 8" Style="{DynamicResource LoadingTextBoxStyle }"></TextBox>
                        <PasswordBox x:Name="txtPassWord" Grid.Row="1" Grid.Column="1" Grid.ColumnSpan="2" Margin="6 8 10 8" Style="{DynamicResource LoadingPasswordBoxStyle}"></PasswordBox>
                        <Button x:Name="StartUpdate" Command="{Binding UpdateCommand}"  Grid.Row="2"   Content="更新用户ID" FontSize="18" VerticalAlignment="Bottom" HorizontalAlignment="Stretch" Style="{DynamicResource ButtonStyle}" Margin="45.02,0,57.933,-4.625" Width="Auto" Height="26"  Grid.ColumnSpan="2"/>
                        <Button x:Name="btnStopUpdate" Command="{Binding StopUpdateCommand}" Grid.Row="2"  Content="停止更新ID"  Grid.Column="2" FontSize="18" VerticalAlignment="Bottom" HorizontalAlignment="Stretch" Style="{DynamicResource ButtonStyle}" Margin="-18.744,0,38.327,-3.125" Width="Auto" Height="26" />
                    </Grid>
                </Grid>
            </Border>
        </Grid>
    </Grid>
</Window>
using GalaSoft.MvvmLight;
using GalaSoft.MvvmLight.Command;
using GalaSoft.MvvmLight.Messaging;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Threading; namespace MvvmLightDemo.ViewModel
{
public class LoadViewModel: ViewModelBase
{
private RelayCommand updateCommand; private RelayCommand stopUpdateCommand; private string userId; /// <summary>
/// 属性,用户ID
/// </summary>
public string UserId
{
get { return userId; }
// MvvmLight实现的Set方法,好处就是不用自己实现RaisePropertyChanged函数了,属性跟改后也可以通知到View端;
set { Set(ref userId, value); }
}
/// <summary>
/// 更新ID命令
/// </summary>
public RelayCommand UpdateCommand
{
set { updateCommand = value; }
get
{
if (updateCommand==null)
{
updateCommand = new RelayCommand(()=>ExecuteUpdate());
}
return updateCommand;
}
} /// <summary>
/// 停止更新ID命令
/// </summary>
public RelayCommand StopUpdateCommand
{
set { stopUpdateCommand = value; }
get
{
if (stopUpdateCommand==null)
{
stopUpdateCommand = new RelayCommand(()=>ExecuteStopUpdate());
}
return stopUpdateCommand;
}
} private void ExecuteStopUpdate()
{
            //发送消息给View端
Messenger.Default.Send<string>("","StopUpdate");
} private void ExecuteUpdate()
{
            //发送消息给View端
Messenger.Default.Send<string>(UserId, "Update");
} }
}
using GalaSoft.MvvmLight;
using GalaSoft.MvvmLight.Ioc;
using Microsoft.Practices.ServiceLocation;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks; namespace MvvmLightDemo.ViewModel
{
public class ViewModelLocator
{
public ViewModelLocator()
{
//所有的View都可以到Locator中找到自己需要的VM层,这个Locator相当于一个索引器
// Locator层返回的VM层是单例形式的,避免了由于代码问题导致的内存泄漏 ServiceLocator.SetLocatorProvider(() => SimpleIoc.Default);
if (ViewModelBase.IsInDesignModeStatic)
{
// 在Visual Studio中设计预览Xaml文件的时候,在这里注册会起作用;
SimpleIoc.Default.Register<LoadViewModel>();
}
else
{
// 在运行时,在这里注册会起作用;
SimpleIoc.Default.Register<LoadViewModel>();
} // 更多的时候,默认在这里注册就可以了;
SimpleIoc.Default.Register<LoadViewModel>();
} //返回一个LoadViewModel的实例,通过前端即xmal.cs获取
public LoadViewModel LoadVM_Instance
{
get
{
return ServiceLocator.Current.GetInstance<LoadViewModel>();
}
} public static void Cleanup()
{
// TODO Clear the ViewModels
}
}
}
using GalaSoft.MvvmLight.Messaging;
using MvvmLightDemo.Model;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using System.Windows.Threading; namespace MvvmLightDemo
{
/// <summary>
/// LoadWindwo.xaml 的交互逻辑
/// </summary>
public partial class LoadWindow : Window
{
private DispatcherTimer timerUpdate = new DispatcherTimer();
public LoadWindow()
{
InitializeComponent();
Messenger.Default.Register<string>(this,"Update",UpdateMethod);
Messenger.Default.Register<string>(this,"StopUpdate",StopUpdateMethod);
} private void StopUpdateMethod(string obj)
{
MessageBox.Show("停止更新");
timerUpdate.Stop();
} private void UpdateMethod(string obj)
{
MessageBox.Show("开始更新");
timerUpdate.Start();
} private void LoginMethod(string obj)
{
btnLogin_Click(null,null);
} private void Title_Loaded(object sender, RoutedEventArgs e)
{
timerUpdate.Interval = TimeSpan.FromMilliseconds(500);
timerUpdate.Tick += new EventHandler(timerUpdate_Trick);
timerUpdate.Stop();
} private void timerUpdate_Trick(object sender, EventArgs e)
{
Random rand = new Random();
this.txtUserId.Text = rand.Next(1000).ToString();
} private void Title_Unloaded(object sender, RoutedEventArgs e)
{
timer.Stop();
} }
}
 
 点击更新按钮,UserId定时更新
 
赋源代码下载地址:
 

MvvmLight框架的基本使用的更多相关文章

  1. MVVMlight框架应用:Data Binding、Command

    常用Wpf开发中我们在ViewModel中实现INotifyPropertyChanged接口,通过触发PropertyChanged事件达到通知UI更改的目的:在MVVMLight框架里,这里我们定 ...

  2. MvvmLight框架使用入门(一)

    MvvmLight是比较流行的MVVM框架,相对较为简单易用.可能正因为简单,对应的帮助文档不多,对初学者就不够友好了.这里会用几篇随笔,就个人对MvvmLight的使用经验,来做一个入门的介绍. 第 ...

  3. 通过Nuget添加Mvvmlight框架发生错误

    IDE:Visual Studio 2013 场景:通过Nuget添加Mvvmlight框架 具体错误: 解决办法:删除Nuget,然后添加新版本的Nuget Package Manager 具体操作 ...

  4. MvvmLight框架使用入门(四)

    本篇我们着重介绍ViewModelBase,演示Set和RaisePropertyChanged方法的使用,以及就Cleanup方法释放资源展开讨论. ICleanup 接口.实现该接口的ViewMo ...

  5. MvvmLight框架使用入门(三)

    本篇是MvvmLight框架使用入门的第三篇.从本篇开始,所有代码将通过Windows 10的Universal App来演示.我们将创建一个Universal App并应用MvvmLight框架. ...

  6. MvvmLight框架使用入门(二)

    上一篇我们简单对MvvmLight做了介绍.罗列了三个DLL中,各个命名空间下主要类的定义及大致作用.因为只是范范的概论,对于从未接触过MvvmLight的萌新来说,根本就是在晃点他们.不过万事开头难 ...

  7. MvvmLight框架使用入门(5)

    上一次写MvvmLight框架使用入门(4)的时候还在用Visual Studio 2015,我儿子也不会过来盖上我的XPS……重启这个系列一方面是因为最近又开始写UWP的东西了,另一个是因为Mvvm ...

  8. MVVMLight学习笔记(二)---MVVMLight框架初探

    一.MVVM分层概述 MVVM中,各个部分的职责如下: Model:负责数据实体的结构处理,与ViewModel进行交互: View:负责界面显示,与ViewModel进行数据和命令的交互: View ...

  9. 在MVVMLight框架的ViewModel中实现NavigationService

    网上已经有很多方法了,比如通过Messenger来实现等等.这里我只讲述一种我比较喜欢的方法,因为它很方便 首先定义一个ViewModel基类,将所有ViewModel子类继承这个基类.在基类中定义 ...

随机推荐

  1. 第九十八篇:Web的储存机制LocalStorage

    好家伙 1.什么是LocalStorage? LocalStorage 是一种 web 端的存储机制, 它使得由 JavaScript 编写的网站或者应用可以无限期的在浏览器中存储并访问数据. Loc ...

  2. Spark 写 Hbase

    package com.grady import org.apache.hadoop.hbase.HBaseConfiguration import org.apache.hadoop.hbase.c ...

  3. 重复造轮子 SimpleMapper

    接手的项目还在用 TinyMapper 的一个早期版本用来做自动映射工具,TinyMapper 虽然速度快,但在配置里不能转换类型,比如 deleted 在数据库中用 0.1 表示,转换成实体模型时没 ...

  4. kali2020.1修改root密码,以最高权限登录系统

    普通用户权限登录系统 sodu su切换为root权限 passwd root 按提示输入密码 再次输入密码 更新密码 右上角点切换用户 root/xxxx 更改成功,下面公布操图片

  5. 2.69分钟完成BERT训练!新发CANN 5.0加持

    摘要:快,着实有点快. 现在,经典模型BERT只需2.69分钟.ResNet只需16秒. 啪的一下,就能完成训练! 本文分享自华为云社区<这就是华为速度:2.69分钟完成BERT训练!新发CAN ...

  6. nginx配置文件中location的三个匹配规则定义

    #直接匹配网站根,通过域名访问网站首页比较频繁,使用这个会加速处理,官网如是说. #这里是直接转发给后端应用服务器了,也可以是一个静态首页 # 第一个必选规则 location = / { #prox ...

  7. Elastic:使用ElastAlert发送通知

    ElastAlert是一个简单的框架,用于从Elasticsearch中的数据中发出异常,尖峰或其他感兴趣模式的警报.我们可以在地址https://elastalert.readthedocs.io/ ...

  8. 查看当前看k8s集群支持的版本命令

    # kubectl api-versions admissionregistration.k8s.io/v1 admissionregistration.k8s.io/v1beta1 apiexten ...

  9. 关于aws cli命令的exit/return code分析

    最近总是收到一个备份脚本的失败邮件,脚本是之前同事写的,没有加入任何有调试信息,及有用的日志 于是去分析 ,脚本中有一条 aws s3 sync $srclocal  $dsts3 命令,然后根据这条 ...

  10. C++面向对象编程之类模板、函数模板等一些补充

    1.static数据 和 static函数: 对于 非static函数 在内存中只有一份,当类对象调用时,其实会有该对象的this pointer传进去,那个函数就知道要对那个对象进行操作: stat ...