MVVM Light使用教程
参考教程:
1.https://www.cnblogs.com/manupstairs/p/4890300.html
2.https://www.cnblogs.com/manupstairs/p/4909585.html
3.https://www.cnblogs.com/manupstairs/p/4928888.html
4.https://www.cnblogs.com/manupstairs/p/4948347.html
5.https://www.cnblogs.com/manupstairs/p/13661227.html
-----适合小型项目,简化版结构,不使用Locator,直接在XAML中设置DataContext
1.创建 WPF 项目
打开 Visual Studio 并创建一个新的 WPF 应用项目。
2.安装 MVVM Light
在解决方案资源管理器中,右击项目名称,选择“管理 NuGet 包”。
在 NuGet 包管理器中搜索 MvvmLightLibs 并安装该包。
3.创建 ViewModel
在项目中添加一个新的类文件,命名为 MainViewModel.cs。
让这个类继承自 ViewModelBase 类,添加一个属性用于数据绑定、添加一个Command命令:
using GalaSoft.MvvmLight;
public class MainViewModel : ViewModelBase
{
public MainViewModel()
{
UpdateMessageCommand = new RelayCommand(UpdateMessage);
}
private string _welcomeMessage = "Hello, MVVM Light!";
public string WelcomeMessage
{
get => _welcomeMessage;
set => Set(ref _welcomeMessage, value, , nameof(WelcomeMessage));
//在使用 MVVMLight 框架时,通常不需要直接调用 RaisePropertyChanged 方法,因为 MVVMLight 的
ViewModelBase 类已经为您处理了属性更改通知。您只需要在属性的 setter 方法中使用 Set 方法,并传入属性字段
的引用和新值,Set 方法会自动触发属性更改通知。
}
public RelayCommand UpdateMessageCommand { get; }
private void UpdateMessage()
{
WelcomeMessage = "Message updated!";
}
}4.设置 DataContext
修改 MainWindow.xaml 的 XAML 代码,以将 DataContext 设置为 MainViewModel 的实例(非共享,每个独立,可以使用Locator共享MainViewModel):
<Window x:Class="YourNamespace.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:YourNamespace"
xmlns:vm="clr-namespace:PictureStitching.ViewModel" <!-- 添加这个,如果ViewModel在子命名空间下 -->
Title="MainWindow" Height="350" Width="525">
<Window.DataContext>
<vm:MainViewModel />
</Window.DataContext>
<Grid>
<TextBlock Text="{Binding WelcomeMessage}" />
<Button Content="Update Message" Command="{Binding UpdateMessageCommand}" />
</Grid>
</Window> 