手动搭建一个简单的MVVMLight框架的方法

本章讲述:手动搭建一个简单的MVVMLight框架步骤:

1、下载MVVMLight所需要的dll库文件

    主要文件包括:CommonServiceLocator.dll、GalaSoft.MvvmLight.dll、GalaSoft.MvvmLight.Extras.dll、GalaSoft.MvvmLight.Platform.dll、System.Windows.Interactivity.dll

    下载地址:

2、新建项目,项目名称为:“DSViewerTooling”,在项目中引用下载的dll库文件,新建文件夹“Model”、“View”和“ViewModel”;

3、添加类文件“MainViewModel”   

    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;

    namespace DSViewerTooling.ViewModel
    {
        public class MainViewModel : ViewModelBase
        {

        }
    }

4、添加类文件“ViewModelLocator”

    using CommonServiceLocator;
    using GalaSoft.MvvmLight;
    using GalaSoft.MvvmLight.Ioc;
    namespace DSViewerTooling.ViewModel
    {
        public class ViewModelLocator
        {
            /// <summary>
            /// Initializes a new instance of the ViewModelLocator class.
            /// </summary>
            public ViewModelLocator()
            {
                ServiceLocator.SetLocatorProvider(() => SimpleIoc.Default);
                SimpleIoc.Default.Register<MainViewModel>();
            }

            public MainViewModel Main
            {
                get { return ServiceLocator.Current.GetInstance<MainViewModel>(); }
            }            

            public static void Cleanup()
            {
                // TODO Clear the ViewModels
            }
        }
    }

项目文件结构图:

5、修改“App.xaml”文件

<Application x:Class="DSViewerTooling.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"
             d1p1:Ignorable="d"
             xmlns:d1p1="http://schemas.openxmlformats.org/markup-compatibility/2006"
             StartupUri="MainWindow.xaml">
    <Application.Resources>
        <ResourceDictionary>
            <vm:ViewModelLocator x:Key="Locator" d:IsDataSource="True" xmlns:vm="clr-namespace:DSViewerTooling.ViewModel" />
        </ResourceDictionary>
    </Application.Resources>
</Application>

首先View和ViewModel之间不再直接引用,而是通过ViewModelLocator关联,

其次储存在ViewModelLocator里的ViewModel类似于单例的存在,可以在全局引用绑定。

同时避免了某些情况下频繁创建ViewModel,却未做好资源释放造成的内存泄漏。(这里并不是说所有的ViewModel都必须放到ViewModelLocator)

下面我们来看下Command是如何绑定的,通知PropertyChanged以及ViewModelBase类 。

MvvmLight的ViewModelBase很有意思,继承了INotifyPropertyChanged接口,并提供了一个Set方法来给属性赋值,简单理解就是不用自己在ViewModel实现INotifyPropertyChanged,然后在属性赋值时通知了。

6、绑定MainWindow.xaml到ViewModelLocator中的Main

<Window x:Class="DSViewerTooling.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="MainWindow" Height="350" Width="525"
        DataContext="{Binding Main ,Source={StaticResource Locator}}">
    <StackPanel VerticalAlignment="Center">
        <TextBlock Text="{Binding Title}" FontFamily="微软雅黑" Foreground="Black" FontSize="25" HorizontalAlignment="Center" VerticalAlignment="Center"/>
        <Button Margin="30" Width="80" Height="35" Content="改变文本" Command="{Binding ChangeTitleCmd}"/>
    </StackPanel>
</Window>

7、属性和ICommand定义声明,在MainViewModel.cs

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.Input;

namespace DSViewerTooling.ViewModel
{

    public class MainViewModel : ViewModelBase
    {
        private string title = "Hello MVVMLight,Hello C#";
        public string Title
        {
            get { return title; }
            set { title = value; RaisePropertyChanged(); }
        }
        #region        
        private ICommand m_ChangeTitleCmd;
        public ICommand ChangeTitleCmd
        {
            get
            {
                return m_ChangeTitleCmd ?? (m_ChangeTitleCmd = new RelayCommand(() =>
                {
                    Title = "chanage title command";
                }));
            }
        }
        #endregion
    }
}

8、运行结果图,右图为点击按钮改变文本框显示ICommand 命令响应;

     

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
好的,我可以为您举一个简单的例子来搭建一个WPF MVVM框架,使用MVVMLight框架。 首先,我们需要创建一个新的WPF项目。然后,我们需要添加MVVMLight库的引用。您可以通过NuGet管理器来添加,也可以手动下载并添加引用。 接下来,我们需要创建模型(Model)。模型是表示数据和业务逻辑的类。我们可以创建一个名为“Person”的模型类,包含Name和Age属性,如下所示: ```csharp public class Person { public string Name { get; set; } public int Age { get; set; } } ``` 然后,我们需要创建视图模型(ViewModel)类。视图模型是连接视图和模型的桥梁。我们可以创建一个名为“MainViewModel”的视图模型类,继承自MVVMLight框架中的ViewModelBase类。在该视图模型类中,我们需要定义一个ObservableCollection属性,用于存储Person对象,以及一些命令,用于添加和删除Person对象。 ```csharp public class MainViewModel : ViewModelBase { private ObservableCollection<Person> _persons; public MainViewModel() { // 初始化Persons集合 _persons = new ObservableCollection<Person>(); } public ObservableCollection<Person> Persons { get { return _persons; } set { Set(ref _persons, value); } } public ICommand AddPersonCommand { get { return new RelayCommand(() => { // 添加Person对象 _persons.Add(new Person()); }); } } public ICommand DeletePersonCommand { get { return new RelayCommand<Person>((person) => { // 删除Person对象 _persons.Remove(person); }); } } } ``` 接下来,我们需要创建视图(View)。视图是用户界面(UI),我们可以使用XAML编写UI。我们可以创建一个名为“MainWindow”的视图,并在其中添加一些控件,如下所示: ```xaml <Window x:Class="MvvmLightSample.MainWindow" 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:vm="clr-namespace:MvvmLightSample.ViewModel" mc:Ignorable="d" Title="MainWindow" Height="450" Width="800"> <Window.DataContext> <vm:MainViewModel/> </Window.DataContext> <Grid> <Grid.RowDefinitions> <RowDefinition Height="Auto"/> <RowDefinition Height="*"/> </Grid.RowDefinitions> <StackPanel Orientation="Horizontal" Margin="10"> <Button Content="Add" Margin="10" Command="{Binding AddPersonCommand}"/> <Button Content="Delete" Margin="10" Command="{Binding DeletePersonCommand}" CommandParameter="{Binding ElementName=personListBox, Path=SelectedItem}"/> </StackPanel> <ListBox Grid.Row="1" Margin="10" Name="personListBox" ItemsSource="{Binding Persons}" DisplayMemberPath="Name"/> </Grid> </Window> ``` 在该视图中,我们使用了DataBinding将视图和视图模型类连接起来。我们将视图模型类的实例设置为视图的DataContext属性,然后在视图中绑定视图模型类的属性和命令。 最后,我们需要在App.xaml.cs文件中启动应用程序,如下所示: ```csharp public partial class App : Application { protected override void OnStartup(StartupEventArgs e) { base.OnStartup(e); // 启动MVVMLight框架 ServiceLocator.SetLocatorProvider(() => SimpleIoc.Default); SimpleIoc.Default.Register<MainViewModel>(); } } ``` 现在,我们已经完成了一个简单的WPF MVVM应用程序,使用了MVVMLight框架。当我们运行该应用程序时,会显示一个包含两个按钮和一个列表框的窗口。当我们单击“Add”按钮时,会在列表框中添加一个空的Person对象;当我们单击“Delete”按钮时,会删除选定的Person对象。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值