WordPad 2.0
上一期实现了一虽然建议但是功能比较全面的Wordpad程序,但是程序代码略显繁琐,这一期更新改进版。
MainWindows.xaml
添加 <Window.CommandBindings>节点,响应保存和关闭命令
<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; } }
邮件菜单,快捷键,状态控制等功能已经全部实现
所有功能都是通过Command来驱动的
用到的Command
ApplicationCommands.Save
ApplicationCommands.Paste
ApplicationCommands.Cut
ApplicationCommands.Save
ApplicationCommands.Close
TextBox直接支持前三种命令(WordPad1.0中原版使用的是TextBlock,不支持这三种命令,小编手滑,勿用了TextBox)
保存和关闭命令需要有响应的命令处理函数,首先设置Menu和ToolBar的Command属性,通过Command Binding关联Command和处理函数
执行Command时,会触发Execute事件。触发CanExecute事件时,事件处理函数需要返回CanExecute属性,告知系统是否可用
To be continue...