6.命令的使用
Prism框架提供了DelegateCommand类型,专门用于进行WPF中的行为处理。
基本使用
一、命令的使用
DelegateCommand(Action executeMethod):DelegateCommand的构造函数,创建DelegateCommand对象。
executeMethod:无参的命令执行函数。
定义命令
public class MainViewModel { public ICommand BtnCommand => new DelegateCommand(Execute); private void Execute() { //做命令执行业务 MessageBox.Show("执行指令"); } }
xaml中绑定命令
<Window x:Class="_2_PrismApplication启动.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:_2_PrismApplication启动" mc:Ignorable="d" Title="MainWindow" Height="450" Width="800"> <Grid> <Button Command="{Binding BtnCommand}" Content="Button" HorizontalAlignment="Left" Height="61" Margin="145,139,0,0" VerticalAlignment="Top" Width="153"/> </Grid> </Window>
以上做法就能实现最简单的命令了,缺点是无法进行命令状态检查。
带参数的命令
Prism框架中,命令的使用跟MVVMToolkit框架是类似的,命令的执行函数可以有参,也可以无参,具体用法如下:
public ICommand BtnCommand => new DelegateCommand<string>(Execute); private async void Execute(string str) { await Task.Delay(2000); Value = 100; }
UI绑定
<Button Command="{Binding BtnCommand}" CommandParameter="{Binding Value123}" Content="Button" HorizontalAlignment="Left" Height="61" Margin="145,139,0,0" VerticalAlignment="Top" Width="153"/>

浙公网安备 33010602011771号