C#学习笔记-WPF框架(MvvmLight)

1.框架引用

  1.1 MvvmLight

  1.2 MvvmLight+PropertyChanged.Fody

  在项目中,添加NuGet程序包,浏览处,查找MvvmLight程序包和PropertyChanged.Fody程序包,安装配置到项目中。添加完这些NuGet程序包之后,项目中会有一个ViewModel的文件夹,包含了ViewModelLocator、MainViewModel两个文件,以及在app.xmal文件中添加了一个资源引用。

   ViewModelLocator:相当于一个管理全局ViewModel的一个类,有点类似于IOC容器

        public ViewModelLocator()
        {
            ServiceLocator.SetLocatorProvider(() => SimpleIoc.Default);

            SimpleIoc.Default.Register<MainViewModel>();//类似于IOC容器一样注册ViewModel
        }

        //获取ViewModel的实例
        public MainViewModel Main
        {
            get
            {
                return ServiceLocator.Current.GetInstance<MainViewModel>();
            }
        }

 

   MainViewModel:一个ViewMode,继承自ViewModelBase,属性通过配置RaisePropertyChanged()方法(数据驱动),发生改变时可在view中同步更新。

        public string Name
        {
            get { return name; }
            set
            {
                name = value;
                this.RaisePropertyChanged();//属性数据通知(MVVM数据驱动)
            }
        }

    Mvvm的数据驱动,在MvvmLight框架中,RelayCommand 表现出来

  public RelayCommand SendShow => new RelayCommand(send);

绑定数据驱动和事件驱动,DataContext绑定Locator,Path路径获取ViewModel

<Window x:Class="MVVMLight.Demo.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:local="clr-namespace:MVVMLight.Demo"
        mc:Ignorable="d"
        DataContext="{Binding Source={StaticResource Locator},Path=Main}"
        Title="MainWindow" Height="450" Width="800">
    <Grid>
        <TextBox Text="{Binding Name}"/>
        <Button x:Name="button" Content="Button" HorizontalAlignment="Left" Margin="176,130,0,0" VerticalAlignment="Top" Width="75" Command="{Binding SendShow}"/>
    </Grid>
</Window>

2.MvvmLight+PropertyChanged.Fody

       PropertyChanged.Fody框架可以为属性添加INotifyPropertyChanged的属性设置,在类前面添加一个特性标签[AddINotifyPropertyChangedInterface],当view中绑定的通知属性发生改变时,view界面可同步更新。

using GalaSoft.MvvmLight.Command;
using PropertyChanged;
namespace MVVMLight.Demo.ViewModel
{
    //MvvmLight+PropertyChanged.Fody减少对属性配置
    [AddINotifyPropertyChangedInterface]
    public class CViewModel
    {
        private string name;

        public string Name
        {
            get { return name; }
            set
            {
                name = value;
            }
        }
        private void send()
        {
            Name = "张三";
        }
        public RelayCommand SendShow => new RelayCommand(send);

    }
}

  • 0
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值