WPF 简单文本编辑器
这与注释的部分二选一
<Window.CommandBindings> <CommandBinding Command="ApplicationCommands.Save" Executed="SaveCommand_Executed" CanExecute="SaveCommand_CanExecute"></CommandBinding> </Window.CommandBindings>
菜单栏
<Menu Grid.Row="0"> <MenuItem Header="File"> <MenuItem Command="New"></MenuItem> <MenuItem Command="Open"></MenuItem> <MenuItem Command="Save"></MenuItem> <MenuItem Command="SaveAs"></MenuItem> <Separator></Separator> <MenuItem Command="Close"></MenuItem> </MenuItem> </Menu>
工具栏
<ToolBarTray Grid.Row="1"> <ToolBar> <Button Command="New">New</Button> <Button Command="Open">Open</Button> <Button Command="Save">Save</Button> </ToolBar> <ToolBar> <Button Command="Cut">Cut</Button> <Button Command="Copy">Copy</Button> <Button Command="Paste">Paste</Button> </ToolBar> </ToolBarTray>
文本框
<TextBox Name="txt" Margin="5" Grid.Row="2" TextWrapping="Wrap" AcceptsReturn="True" TextChanged="txt_TextChanged"></TextBox>
代码(绑定部分)
CommandBinding binding; binding = new CommandBinding(ApplicationCommands.New); binding.Executed += NewCommand; this.CommandBindings.Add(binding); binding = new CommandBinding(ApplicationCommands.Open); binding.Executed += OpenCommand; this.CommandBindings.Add(binding); //binding = new CommandBinding(ApplicationCommands.Save); //binding.Executed += SaveCommand_Executed; //binding.CanExecute += SaveCommand_CanExecute; //this.CommandBindings.Add(binding);
设置一个bool量,表示是否文本有变化
1 private bool isDirty = false;
命令
1 private void NewCommand(object sender, ExecutedRoutedEventArgs e) 2 { 3 MessageBox.Show("New command triggered with " + e.Source.ToString()); 4 isDirty = false; 5 } 6 private void OpenCommand(object sender, ExecutedRoutedEventArgs e) 7 { 8 isDirty = false; 9 } 10 private void SaveCommand_Executed(object sender, ExecutedRoutedEventArgs e) 11 { 12 MessageBox.Show("Save command triggered with " + e.Source.ToString()); 13 isDirty = false; 14 } 15 16 private void txt_TextChanged(object sender, RoutedEventArgs e) 17 { 18 isDirty = true; 19 } 20 private void SaveCommand_CanExecute(object sender, CanExecuteRoutedEventArgs e) 21 { 22 e.CanExecute = isDirty; 23 }