Commands-Notes (-) and commands
Command-Note (-)
Basic Concepts
Basic elements of the command:
Command steps:
Second test
To achieve this requirement, define a command and use the Button to send this command. When the command reaches the Textbox, clear the Text (when the Textbox is empty, the Button is unavailable ).
XAML code:
<Window x:Class="CommandApplication.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:CommandApplication"
mc:Ignorable="d"
Title="MainWindow" Height="175" Width="200">
<StackPanel x:Name="stackPanel">
<Button x:Name="button1" Content="Send Command" Margin="5"/>
<TextBox x:Name="textBoxA" Margin="5,0" Height="100"/>
</StackPanel>
</Window>
CS code:
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 CommandApplication
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
Public partial class MainWindow : Window
{
Public MainWindow()
{
InitializeComponent();
InitializeCommand();
}
//RoutedCommand is a common command class that comes with the system.
/ / Declare the command instance
Private RoutedCommand clearCmd = new RoutedCommand("Clear", typeof(MainWindow));
Private void InitializeCommand()
{
/ / specify the command source
this.button1.Command = this.clearCmd;
this.clearCmd.InputGestures.Add(new KeyGesture(Key.C, ModifierKeys.Alt));
/ / Specify the command target, specify the s in the command source properties
this.button1.CommandTarget = this.textBoxA;
/ / Create a command association
CommandBinding cb = new CommandBinding();
cb.Command = this.clearCmd;
cb.CanExecute += new CanExecuteRoutedEventHandler(cb_CanExecute);
cb.Executed += new ExecutedRoutedEventHandler(cb_Execute);
//this.stackPanel.CommandBindings.Add(cb);
this.textBoxA.CommandBindings.Add(cb);
}
//This method is called when the command is delivered to the target.
Private void cb_Execute(object sender, ExecutedRoutedEventArgs e)
{
this.textBoxA.Clear();
e.Handled = true;
}
/ / This method is called when the probe command is executable
Private void cb_CanExecute(object sender, CanExecuteRoutedEventArgs e)
{
If (string.IsNullOrEmpty(this.textBoxA.Text))
{ e.CanExecute = false; }
Else
{ e.CanExecute = true; }
e.Handled = true;
}
}
}
Running effect: