WPF MVVM简单介绍和使用
MVVM简介
MVVM是Model-View-ViewModel的简写,分为视图(View)、视图模型(ViewModel)、模型(Model)三部分。MVVM 模式就是将其中的View 的状态和行为抽象化,形成数据绑定和命令,将视图 UI 和业务逻辑分开。
由ViewModel处理相关的业务逻辑,与View对应,负责获取和更新Model的数据。
WPF中常用的MVVM框架
- mvvmlight(目前已经停止维护,适用于Net framework版本下的WPF程序,如果要在net5或者更新的net版本使用,可以使用新的CommunityToolkit.Mvvm包)
- prism —https://github.com/PrismLibrary/Prism
- Stylet —https://github.com/canton7/Stylet
MVVM在WPF实现
MVVM模式大部分主要通过绑定(Binding)和命令(Command)来实现。
代码示例:
MainWindow的Xaml代码(只附了Grid中的代码)
<Grid>
<TextBlock
Margin="61,74,0,0"
HorizontalAlignment="Left"
VerticalAlignment="Top"
Text="状态:"
TextWrapping="Wrap" />
<TextBlock
Margin="115,74,0,0"
HorizontalAlignment="Left"
VerticalAlignment="Top"
Text="{Binding Status}"
TextWrapping="Wrap" />
<TextBlock
Margin="53,157,0,0"
HorizontalAlignment="Left"
VerticalAlignment="Top"
Text="输入状态:"
TextWrapping="Wrap" />
<TextBox
Width="120"
Margin="115,157,0,0"
HorizontalAlignment="Left"
VerticalAlignment="Top"
Text="{Binding InStatus, Mode=OneWayToSource}"
TextWrapping="Wrap" />
<Button
Width="43"
Height="22"
Margin="192,234,0,0"
HorizontalAlignment="Left"
VerticalAlignment="Top"
Command="{Binding ChangeCommand}"
Content="改变" />
</Grid>
MainWindow的ViewModel代码:
public class MainWindowViewModel : INotifyPropertyChanged
{
#region 属性
private string _status;
public string Status
{
get
{
return _status;
}
set
{
_status = value;
//实现数据更新,向界面推送
OnPropertyChanged();
}
}
public string InStatus { get; set; }
#endregion
#region 命令
public ICommand ChangeCommand
{
get
{
return new CommandBase(o =>
{
Status = InStatus;
});
}
}
#endregion
public MainWindowViewModel()
{
Status = "初始化";
}
#region 基础实现
//INotifyPropertyChanged接口实现,实现实现变化推送
public event PropertyChangedEventHandler PropertyChanged;
/// <summary>
/// 推送方法(PropertyChanged封装)
/// </summary>
/// <param name="propertyName"></param>
public void OnPropertyChanged([CallerMemberName] string propertyName = "")
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
#endregion
}
MainWindow后台代码(MainWindow.xaml.cs)
只添加了一行代码,将ViewModel赋值给MainWindow的DataContext,将两者进行关联
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
this.DataContext= new MainWindowViewModel();
}
}
运行结果:
点击按钮:
命令基类代码
另外附加实现ICommand
接口的命令简单基类:
public class CommandBase : ICommand
{
public event EventHandler CanExecuteChanged;
private readonly Action<object> _action;
private bool _isEnableExecute = true;
public bool IsEnableExecute
{
get
{
return _isEnableExecute;
}
set
{
if (_isEnableExecute != value)
{
_isEnableExecute = value;
if (CanExecuteChanged != null)
{
CanExecuteChanged(this, new EventArgs());
}
}
}
}
public CommandBase(Action<object> action)
{
if (action == null)
{
return;
}
_action = action;
}
public bool CanExecute(object parameter)
{
return _isEnableExecute;
}
public void Execute(object parameter)
{
_action(parameter);
}
}