WPF learning path (5) Example: wordboard (continued), wpf Road
WordPad 2.0
In the previous issue, a Wordpad program with comprehensive functions was implemented, but the program code was slightly cumbersome. The Community version was updated in this issue.
MainWindows. xaml
Add the <Window. CommandBindings> node, and save and close the command in response.
<Window.CommandBindings> <CommandBinding Command="Close" Executed="CloseCommand" /> <CommandBinding Command="Save" Executed="SaveCommand" CanExecute="SaveCanExecute" /></Window.CommandBindings>
Menu
<MenuItem Header="File"> <MenuItem Header="Copy" Command="Copy" /> <MenuItem Header="Paste" Command="Paste" /> <MenuItem Header="Cut" Command="Cut" /> <Separator></Separator> <MenuItem Header="Save" Command="Save" /> <MenuItem Header="Close" Command="Close" /></MenuItem>
Tool
<ToolBar Grid.Row="1"> <Button Command="Copy"> <Image Source="/Images/Copy16x16.png" /> </Button> <Button Command="Paste"> <Image Source="/Images/Paste16x16.png" /> </Button> <Button Command="Cut"> <Image Source="/Images/Cut16x16.png" /> </Button> <Button Command="Save"> <Image Source="/Images/Save16x16.png" /> </Button> <Button Command="Close"> <Image Source="/Images/Close16x16.png" /> </Button></ToolBar>
TextBox
<TextBox Grid.Row="2" AcceptsReturn="True" TextChanged="TextBox_TextChanged" />
MainWindow. xmal. cs
public partial class MainWindow : Window{ private bool isDirty = false; public MainWindow() { InitializeComponent(); } private void CloseCommand(object sender, ExecutedRoutedEventArgs e) { MessageBox.Show("CloseCommand triggered with " + e.Source); App.Current.Shutdown(); } private void SaveCommand(object sender, ExecutedRoutedEventArgs e) { MessageBox.Show("SaveCommand triggered with " + e.Source); isDirty = false; } private void SaveCanExecute(object sender, CanExecuteRoutedEventArgs e) { e.CanExecute = isDirty; } private void TextBox_TextChanged(object sender, TextChangedEventArgs e) { isDirty = true; }}
The mail menu, shortcut keys, Status control, and other functions have been fully implemented.
Analysis
All functions are driven by Command.
Command Used
ApplicationCommands. Save
ApplicationCommands. Paste
ApplicationCommands. Cut
ApplicationCommands. Save
ApplicationCommands. Close
TextBox directly supports the first three commands (TextBlock is used in the original version of WordPad1.0. These three commands are not supported, but TextBox is not used)
To save and close a Command, you must have a response to the Command processing function. First, set the Command attribute of Menu and ToolBar, and associate the Command and processing functions with the Command Binding.
When the Command is executed, the Execute event is triggered. When a CanExecute event is triggered, the event processing function must return the CanExecute attribute to indicate whether the system is available.
To be continue...