首先创建一个MyCommand类
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Input;
namespace WPFTest
{
public class Mycommand : ICommand
{
//创建委托类型,用于后面接收构造函数里面的参数
Action executeAction;
public Mycommand(Action action)
{
executeAction = action;
}
public event EventHandler CanExecuteChanged;
//允许执行
public bool CanExecute(object parameter)
{
return true;
}
//把Mycommand接收的委托参数用于执行
public void Execute(object parameter)
{
executeAction();
}
}
}
MainViewMode
主要是写业务的
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
namespace WPFTest
{
public class MainViewModel
{
public MainViewModel()
{
//刚好需要一个委托参数,把Show方法传进去
ShowCommand = new Mycommand(Show);
}
//负责UI与业务之间建立联系
public Mycommand ShowCommand { get; set; }
public void Show()
{
MessageBox.Show("点击了按钮!");
}
}
}
View
<Window x:Class="WPFTest.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:WPFTest"
mc:Ignorable="d"
Title="MainWindow" Height="450" Width="800">
<Grid>
<Button Command="{Binding ShowCommand}"/>
</Grid>
</Window>
MainWindow
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;
namespace WPFTest
{
/// <summary>
/// MainWindow.xaml 的交互逻辑
/// </summary>
public partial class MainWindow : Window
{
public MainWindow()
{
//整个MainViewModel作为数据源传给xmal
this.DataContext = new MainViewModel();
}
}
}