使用Command可以实现UI层跟业务层分离,不必在UI层定义事件方法,近而减少耦合。
1<Window x:Class="WpfCommand.MainWindow"
2 xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
3 xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
4 xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
5 xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
6 xmlns:local="clr-namespace:WpfCommand"
7 mc:Ignorable="d"
8 Title="MainWindow" Height="450" Width="800">
9 <Grid VerticalAlignment="Center">
10 <StackPanel>
11 <TextBox Text="{Binding Name}"></TextBox>
12 <Button Command="{Binding ShowCommand }" Content="Button" Height="100"></Button>
13 </StackPanel>
14 </Grid>
15</Window>1/// <summary>
2/// MainWindow.xaml 的交互逻辑
3/// </summary>
4public partial class MainWindow : Window
5{
6 public MainWindow()
7 {
8 this.DataContext = new MainViewModel();
9 InitializeComponent();
10 }
11}1public class MyCommand : ICommand
2{
3 public event EventHandler CanExecuteChanged;
4 Action executeAction;
5 public MyCommand(Action action)
6 {
7 executeAction = action;
8 }
9 public bool CanExecute(object parameter)
10 {
11 return true;
12 }
13 public void Execute(object parameter)
14 {
15 executeAction();
16 }
17}1public class MainViewModel
2{
3 public MyCommand ShowCommand { get; set; }
4 public String Name { get; set; }
5 public MainViewModel()
6 {
7 Name = "Hello World";
8 ShowCommand = new MyCommand(Show);
9 }
10 public void Show()
11 {
12 Name = "点击了Button";
13 MessageBox.Show(Name);
14 }
15}示例截图
