1.框架引用
1.1 MvvmLight
1.2 MvvmLight+PropertyChanged.Fody
在项目中,添加NuGet程序包,浏览处,查找MvvmLight程序包和PropertyChanged.Fody程序包,安装配置到项目中。添加完这些NuGet程序包之后,项目中会有一个ViewModel的文件夹,包含了ViewModelLocator、MainViewModel两个文件,以及在app.xmal文件中添加了一个资源引用。
ViewModelLocator:相当于一个管理全局ViewModel的一个类,有点类似于IOC容器
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15public 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中同步更新。
1
2
3
4
5
6
7
8
9public string Name { get { return name; } set { name = value; this.RaisePropertyChanged();//属性数据通知(MVVM数据驱动) } }
Mvvm的数据驱动,在MvvmLight框架中,RelayCommand 表现出来
1public RelayCommand SendShow => new RelayCommand(send);
绑定数据驱动和事件驱动,DataContext绑定Locator,Path路径获取ViewModel
1
2
3
4
5
6
7
8
9
10
11
12
13
14<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界面可同步更新。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27using 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); } }
最后
以上就是魁梧蜡烛最近收集整理的关于C#学习笔记-WPF框架(MvvmLight)的全部内容,更多相关C#学习笔记-WPF框架(MvvmLight)内容请搜索靠谱客的其他文章。
发表评论 取消回复