双向绑定是wpf的一大特色,甚至android都开始争相模仿,其中mvvmlight又是mvvm的一个典型代表库,节省了好多onpropertychanged例行代码,本文简单介绍一下数据的双向绑定以及控件方法的绑定,效果就是打开窗口,文本里显示666,点击按钮后变成777,很简单,也是很重要的基础。
1、首先,从nuget引入mvvmlight包,如图,不用怀疑,第一个就是最常用的 ,直接下载安装。
2、安装完毕后,会在解决方案里出现ViewModel文件夹,里面有两个cs文件,MainViewModel.cs和ViewModelLocator.cs(这个没什么用,可以删除)。
3、MainViewModel.cs里就是我们要用到的viewmodel内容了,可以在里面写入属性以及方法的代码,如下:
using GalaSoft.MvvmLight;
using GalaSoft.MvvmLight.Command;
namespace WpfApp8.ViewModel
{
/// <summary>
/// This class contains properties that the main View can data bind to.
/// <para>
/// Use the <strong>mvvminpc</strong> snippet to add bindable properties to this ViewModel.
/// </para>
/// <para>
/// You can also use Blend to data bind with the tool's support.
/// </para>
/// <para>
/// See http://www.galasoft.ch/mvvm
/// </para>
/// </summary>
public class MainViewModel : ViewModelBase
{
/// <summary>
/// Initializes a new instance of the MainViewModel class.
/// </summary>
public MainViewModel()
{
Name = "666";
Command = new RelayCommand(() => {
Name = "777";
});
}
private string name;
public string Name
{
get { return name; }
set
{
name = value;
RaisePropertyChanged("Name");
}
}
public RelayCommand Command { get ; set ; }
}
}
4、然后在mian主窗口实例化MainViewModel,就可以用这个viewmodel类了
this.DataContext = new ViewModel.MainViewModel ();
5、最后在前端也就是xaml里直接使用viewmodel里的属性名称,就可以了
<Window x:Class="WpfApp8.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:WpfApp8"
mc:Ignorable="d"
Title="MainWindow" Height="450" Width="800">
<Grid>
<TextBox HorizontalAlignment="Left" Height="23" Margin="160,141,0,0" TextWrapping="Wrap" Text="{Binding Name}" VerticalAlignment="Top" Width="120"/>
<Button Command="{Binding Command}" Content="Button" HorizontalAlignment="Left" Margin="303,144,0,0" VerticalAlignment="Top" Width="75"/>
</Grid>
</Window>