WPF learning path (6) Command, wpf learning path command
In WPF, the command binding mechanism is a more advanced concept than an event. It divides the functions of an application into multiple tasks, and tasks are triggered in multiple ways.
The Application of Command Binding makes the code more in line with the MVVM mode (Model-View-ViewModel), similar to the MVC mode (Model-View-Control ). The two modes will be described in detail in later blogs. The goal is to better separate the front and back-end logic.
A simple Button
<Button Content="Button" Click="Button_Click" />
private void Button_Click(object sender, RoutedEventArgs e){ MessageBox.Show("Hello WPF");}
The front-end display needs to be associated with the background through the Button_Click method. If you want to better separate the two parts, replace the Click event with the Command
Custom Command
using System;using System.Windows;using System.Windows.Input;public class MyCommand : ICommand{ public bool CanExecute(object parameter) { return true; } public event EventHandler CanExecuteChanged; public void Execute(object parameter) { MessageBox.Show("Hello WPF"); }}
<Button Content="Button" x:Name="btn1" />
public MainWindow(){ InitializeComponent(); btn1.Command = new MyCommand();}
Now the logic has been separated into MyCommand.
Use predefined Command
ApplicationCommands provides many predefined commands.
<Button Content="Button" x:Name="btn2" Command="ApplicationCommands.Close"/>
However, these commands are not implemented ("begin □failed)
Use Command Binding to add Logic
public MainWindow(){ InitializeComponent();var OpenCmdBinding = new CommandBinding( ApplicationCommands.Close, OpenCmdExecuted, OpenCmdCanExecute); this.CommandBindings.Add(OpenCmdBinding);}void OpenCmdExecuted(object target, ExecutedRoutedEventArgs e){ this.Close();}void OpenCmdCanExecute(object sender, CanExecuteRoutedEventArgs e){ e.CanExecute = true;}
Some controls do not have the Command attribute.
<Button Grid.Row="2" Height="100" Width="100" HorizontalAlignment="Left" Content="Decrease" Command="Slider.DecreaseLarge" CommandTarget="{Binding ElementName=slider}"/><Slider Grid.Row="2" x:Name="slider" Width="100"></Slider><Button Grid.Row="2" Height="100" Width="100" HorizontalAlignment="Right" Content="Increase" Command="Slider.IncreaseLarge" CommandTarget="{Binding ElementName=slider}"/>
CommandParameter can pass a value to the command
CommandTarget: The Command target to be triggered.
More about Command
Http://www.cnblogs.com/Curry/archive/2009/07/27/1531798.html
Http://www.cnblogs.com/gaixiaojie/archive/2010/09/01/1815015.html
To be continue...