1 新建wpf程序,通过nuget添加Microsoft.Xaml.Behaviors库
2 创建Base ViewModels文件夹
3 在Base里面创建CommandBase类
using System;
using System.Collections.Generic;
using System.Text;
using System.Windows.Input;
namespace WpfApp3.Base
{
public class CommandBase : ICommand
{
public event EventHandler CanExecuteChanged;
public bool CanExecute(object parameter)
{
return true;
}
public void Execute(object parameter)
{
DoExecute?.Invoke(parameter);
}
public Action<object> DoExecute;
}
}
4 在ViewModels里面创建MainViewModel类
using System;
using System.Collections.Generic;
using System.Text;
using WpfApp3.Base;
namespace WpfApp3.ViewModels
{
public class MainViewModel
{
public CommandBase TestCommand { get; set; }
public MainViewModel()
{
TestCommand = new CommandBase();
TestCommand.DoExecute = new Action<object>(DoAction);
}
private void DoAction(object obj)
{
}
}
}
5 修改MainWindow
<Window x:Class="WpfApp3.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:WpfApp3"
xmlns:behaviour="http://schemas.microsoft.com/xaml/behaviors"
mc:Ignorable="d"
Title="MainWindow" Height="350" Width="800">
<Grid>
<Border Width="100" Height=" 30" Background="Orange">
<behaviour:Interaction.Triggers>
<behaviour:EventTrigger EventName="MouseLeftButtonDown">
<behaviour:InvokeCommandAction Command="{Binding TestCommand}" CommandName="123"/>
</behaviour:EventTrigger>
</behaviour:Interaction.Triggers>
</Border>
</Grid>
</Window>
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using WpfApp3.ViewModels;
namespace WpfApp3
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
this.DataContext = new MainViewModel();
}
}
}
6 运行
注意,该方法没有用CallMethodAction方法直接,这种还要建Command,但不用像CallMethodAction方法那样将事件从view拷贝到viewmodel