First, build a form, create a StackPanel in the form, and then stackpanel inside the button and text box, pay attention to all the controls and containers name
<Grid> <stackpanel name="SP1"Horizontalalignment=" Left"height=" -"margin="0"Verticalalignment="Top"Width="525"> <button name="BTN1"Content="Execommand"height=" A"/> <textbox name="TextBox1"height="284"textwrapping="Wrap"text=""/> </StackPanel> </Grid>
Second, start writing command execution empty
Public Partial classMainwindow:window { PublicMainWindow () {InitializeComponent (); Mingling (); } //you need to declare and define the command .RoutedCommand Command =NewRoutedCommand ("Clear",typeof(MainWindow));//the two parameters in the first one is the name, the second is the type of execution command//Start write command function Public voidmingling () {//command to create a buttonBtn1.command =Command; //defining shortcut KeysCOMMAND.INPUTGESTURES.ADD ((NewKeyGesture (Key.c,modifierkeys.alt));//shortcut keys are alt+c//Specify a command target for a buttonBtn1.commandtarget =TextBox1; //Create a command associationCommandbinding cb =NewCommandbinding ()//commandbinding: Used to link commands and commands to the arrangement logic, such as the same "paste", but paste the text and paste the image of the resolution logic is not the same,{Command=Command,}; Cb. CanExecute+ = Cb_canexecute;//CanExecute: Occurs when the command associated with the commandbinding initiates a check to determine whether this command can be executed on the command target. Cb. executed+=cb_executed; SP1.COMMANDBINDINGS.ADD (CB); } Private voidCb_executed (Objectsender, Executedroutedeventargs e) {textbox1.clear ();//text Box Emptye.handled =true;//Handled: Gets or sets a value that indicates whether the KeyPress event has been processed. Ture if executed, false otherwise } Private voidCb_canexecute (Objectsender, Canexecuteroutedeventargs e) { if(string. Isnullorwhitespace (TextBox1.Text)) {E.canexecute=false; } Else{E.canexecute=true; } e.handled=true; } }
Third, click the button
Before clicking the button:
After clicking the button:
wpf--Execute command empty text box