Commands


WPF has Menu and ToolBar controls that serve the same purpose as the controls you know from Windows Forms: you can start commands. With these controls you can add event handler to fulfill the functionality of the commands. However, you can start commands by selecting menus, clicking toolbar buttons, or by pressing some special keys on the keyboard. To handle all these different input gestures, WPF supplies another feature, commands.

WPF offers some predefined commands with the commands classes ApplicationCommands, EditingCommands, ComponentCommands, and NavigationCommands. All these commands classes are static classes with static properties that return RoutedUICommand objects. For example, some of the ApplicationCommands properties are New, Open, Save, SaveAs, Print, and Close - commands you know from many applications.

To show the commands in action, the following sample of a simple editor includes Menu and ToolBar controls that are connected to commands.

Inside the XAML code of the application, you can assign command bindings to the CommandBindings property by defining CommandBinding elements. The CommandBinding class has the property Command where you can specify an object implementing the ICommand interface, and the events CanExecute and Executed to specify event handlers. With the sample application, command bindings are defined within the CommandBindings property of the Window class. The Command properties are set to predefined commands from the ApplicationCommands class. The Executed event is set to the event handler methods that implement the functionality behind the commands. If a command should not be available at all times, you can set the CanExecute event to a handler that decides if the command should be available.

  <Window x:     xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"     xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"     Title="WPFEditor" Height="300" Width="300"     >   <Window.CommandBindings>     <CommandBinding Command="ApplicationCommands.New" Executed="OnFileNew" />     <CommandBinding Command="ApplicationCommands.Open" Executed="OnFileOpen"         CanExecute="OnCanFileOpen" />     <CommandBinding Command="ApplicationCommands.Save" Executed="OnFileSave"         CanExecute="OnCanFileSave" />     <CommandBinding Command="ApplicationCommands.SaveAs" Executed="OnFileSaveAs" />   </Window.CommandBindings> 

Within the window a DockPanel is created to define the layout. Docked on top you can find the Menu control with MenuItem elements. The header is set to define the text of the menu. The _ defines the letter that can be accessed directly with the keyboard without using the mouse. When you pressing the Alt key, the underscore is shown below the letter that follows in the header text. The Command property defines the command associated with the menu item. With the menu items where the property InputGestureText is defined, the command can be accessed quickly with the defined hotkey.

  <DockPanel>   <Menu DockPanel.Dock="Top">     <MenuItem Header="_File">       <MenuItem Name="fileNewMenu" Header="_New" Command="ApplicationCommands.New"           InputGestureText="CTRL+N" />       <MenuItem Name="fileOpenMenu" Header="_Open" Command="ApplicationCommands.Open"           InputGestureText="CTRL+O" />       <Separator />       <MenuItem Name="fileSave" Header="_Save" Command="ApplicationCommands.Save"           InputGestureText="CTRL+S" />       <MenuItem Name="fileSaveAs" Header=Save _As"           Command="ApplicationCommands.SaveAs" />     </MenuItem>   </Menu> 

With the ToolBar element the commands that can be accessed from the toolbar are defined. For arranging the toolbar, the ToolBar element is placed within a ToolBarTray.

      <ToolBarTray DockPanel.Dock="Top">       <ToolBar>         <Button Command="ApplicationCommands.New">           <Image Source="toolbargraphics/New.bmp" />         </Button>         <Button Command="ApplicationCommands.Open">           <Image Source="toolbargraphics/Open.bmp" />         </Button>         <Button Command="ApplicationCommands.Save">           <Image Source="toolbargraphics/Save.bmp" />         </Button>       </ToolBar>     </ToolBarTray>     <TextBox Name="textContent" TextWrapping="Wrap" />   </DockPanel> </Window> 

In the code behind the hander method, OnFileNew() empties the text box and writes the file name untitled.txt to the Title property of the Window class. In OnFileOpen() the Microsoft.Win32 .OpenFileDialog is created and shown as a dialog. With a successful exit of the dialog, the selected file is opened and its content is written to the TextBox control.

Tip 

A dialog for opening a file is not predefined in WPF. You can either create a custom window for selecting files and folders, or you can use the OpenFileDialog class from the Microsoft.Win32 namespace that is a wrapper around the Win32 dialog.

  public partial class Window1 : System.Windows.Window {    private string filename;    private readonly string defaultFilename;    private const string appName = "WPF Simple Editor";    public Window1()    {       defaultFilename =           Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments) +           @"\untitled.txt";       InitializeComponent();       NewFile();    }    private void OnFileNew(object sender, ExecutedRoutedEventArgs e)    {       NewFile();    }    private void NewFile()    {       textContent.Clear();       filename = defaultFilename;       SetTitle();    }    private void SetTitle()    {       Title = System.IO.Path.GetFileName(filename) + " " + appName;    }        private void OnFileOpen(object sender, ExecutedRoutedEventArgs e)    {       try       {          OpenFileDialog dlg = new OpenFileDialog();          bool? dialogResult = dlg.ShowDialog();          if (dialogResult)          {             filename = dlg.FileName;             SetTitle();             textContent.Text = File.ReadAllText(filename);          }       }       catch (IOException ex)       {          MessageBox.Show(ex.Message, "Error WPF Editor", MessageBoxButton.OK,              MessageBoxImage.Error);       }    } 

The application with the opened file sample.txt is shown in Figure 31-17.

image from book
Figure 31-17




Professional C# 2005 with .NET 3.0
Professional C# 2005 with .NET 3.0
ISBN: 470124725
EAN: N/A
Year: 2007
Pages: 427

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net