#346 – No Need to Set Header Property for MenuItem When Using Commands

If you use one of the preexisting RoutedUICommand objects for a WPF command, e.g. ApplicationCommands.Open, you’ll notice that the RoutedUICommand instance has a Text property.  This property in the command is used to set the label appearing on any MenuItem instances that have attached to the command by setting their Command property.  You don’t need to set the menu item’s Header property explicitly.

    <Window.ContextMenu>
        <ContextMenu>
            <MenuItem Command="ApplicationCommands.Open"/>
            <MenuItem Command="ApplicationCommands.Close"/>
            <MenuItem Command="ApplicationCommands.New"/>
        </ContextMenu>
    </Window.ContextMenu>


Notice that the text for each menu item is automatically filled in, since the text strings are defined in the RoutedUICommand object.  Also notice that some of the commands also define key gestures (e.g. Ctrl+O) for executing the command.

#345 – WPF Command Model is Preferred over Traditional Event Handler Model

In an application, you often need to execute some code in response to a user action.  In WPF, you can use the new command model to respond to user actions or you can use the event handler model that Windows Forms used.

In the event handler model, you wire up event handlers to the code that does the actual work.

With this approach, you still have to add all of the individual event handlers and you need to write code to manage state, i.e. figure out when the user is allowed to click the buttons/menus and enable/disable them.

In the WPF command model, a single command object is bound to the handler code and each control links to that command.  The command object also adds support for state.

So the benefits of the WPF command model are:

  • Less plumbing code to write (no event handlers)
  • Automatically handle control enabled/disabled state

#344 – The CommandBinding CanExecute Event Determines Whether a Button is Enabled

When you associate a button’s Command property with a CommandBinding object,and bind the CommandBinding object to both Executed and CanExecute handlers, the Button control will automatically toggle between enabled/disabled, depending on the code in the CanExecute method.

Suppose we create two buttons, binding them to open/close commands.

    <StackPanel Orientation="Horizontal" HorizontalAlignment="Center">
        <Button Content="Open" Command="ApplicationCommands.Open"
                VerticalAlignment="Center" Padding="10,5" Margin="5"/>
        <Button Content="Close" Command="ApplicationCommands.Close"
                VerticalAlignment="Center" Padding="10,5" Margin="5"/>
    </StackPanel>

Then we create a CommandBinding and associated handlers.

		public MainWindow()
		{
			this.InitializeComponent();

            CommandBindings.Add(new CommandBinding(ApplicationCommands.Open, Open_Executed, Open_CanExecute));
            CommandBindings.Add(new CommandBinding(ApplicationCommands.Close, Close_Executed, Close_CanExecute));
        }

        private bool isOpen = false;

        public void Open_Executed(object sender, ExecutedRoutedEventArgs e)
        {
            MessageBox.Show("Open");
            isOpen = true;
        }

        public void Open_CanExecute(object sender, CanExecuteRoutedEventArgs e)
        {
            e.CanExecute = !isOpen;
        }

        public void Close_Executed(object sender, ExecutedRoutedEventArgs e)
        {
            MessageBox.Show("Close");
            isOpen = false;
        }

        public void Close_CanExecute(object sender, CanExecuteRoutedEventArgs e)
        {
            e.CanExecute = isOpen;
        }

The buttons will now automatically be enabled/disabled, depending on the value of isOpen.

#343 – Associating Multiple Controls with the Same Command

One benefit of using commands in WPF, as opposed to writing event handlers, is that it’s easier to link multiple controls to a single command.  With commands, you can create a single command object, bind it to a method, and then associate the command with more than one control by setting the Command property of each control.

In the example below, we associate the ApplicationCommands.Open command with both a Button and a MenuItem.

    <Window.ContextMenu>
        <ContextMenu>
            <MenuItem Header="Open" Command="ApplicationCommands.Open"/>
        </ContextMenu>
    </Window.ContextMenu>

    <StackPanel>
        <Button Content="Open" Command="ApplicationCommands.Open" HorizontalAlignment="Center" />
    </StackPanel>

In the code-behind, we still only have to create a single CommandBinding instance.

		public MainWindow()
		{
			this.InitializeComponent();

            CommandBindings.Add(new CommandBinding(ApplicationCommands.Open, Open_Executed, Open_CanExecute));
        }

        public void Open_Executed(object sender, ExecutedRoutedEventArgs e)
        {
            MessageBox.Show("Open file code goes here");
        }

        public void Open_CanExecute(object sender, CanExecuteRoutedEventArgs e)
        {
            e.CanExecute = true;   // Can we open file?
        }

#342 – Binding a Button to a Command

In WPF, the preferred method for executing some code when a button is clicked is to use a commandA command is an object that represents an action to be taken and is bound to a particular method that performs the action.  The button is then associated with the command by setting its Command property.

Here’s an example.

        <Button Content="Open" Command="ApplicationCommands.Open" />

ApplicationCommands.Open is a predefined command that is just a placeholder that you bind to some “open” logic in your application.  You do this by adding a new CommandBinding object to the parent window’s CommandBindings collection.

You specify handlers for the Executed and CanExecute events of the command.

		public MainWindow()
		{
			this.InitializeComponent();

            CommandBindings.Add(new CommandBinding(ApplicationCommands.Open, Open_Executed, Open_CanExecute));
        }

        public void Open_Executed(object sender, ExecutedRoutedEventArgs e)
        {
            // Open file here
        }

        public void Open_CanExecute(object sender, CanExecuteRoutedEventArgs e)
        {
            e.CanExecute = true;   // Can we open file?
        }

#341 – Create a Button with an Image and Text

Since a Button is a ContentControl, it can have any other control as its content, rather than text.  You can include an Image control, to create a button with an image on its face.  You can also include multiple controls on the button, by settings its main content to be a container, which in turn contains other controls.

In the example below, we create a Button that has both an image and some text (a caption).

        <Button HorizontalAlignment="Center" VerticalAlignment="Center"
                Margin="10" >
            <StackPanel>
                <Image Source="Misc-Settings-icon.png" Height="64" Width="64"/>
                <Label Content="Settings" HorizontalAlignment="Center"/>
            </StackPanel>
        </Button>

#340 – Create a Button with an Image

To create a Button that has an image on the surface of the button, rather than text, you use an Image control as the content of the button.

You need to tell the Image control where to find its image.  The easiest way to locate images is to just include them as resources in your project.

  • Embed the image as a binary resource in your project
  • Set the Build Action of the image to Resource
  • Use the filename as the image’s Source

In the example below, we’ve added the Misc-Settings-icon.png file to our project.

We can then create a Button that has this image as its main content.  Because Button is a ContentControl, it can contain another control as its content.

    <StackPanel>
        <Button HorizontalAlignment="Center" VerticalAlignment="Center"
                Margin="10" >
            <Image Source="Misc-Settings-icon.png" Height="64" Width="64"/>
        </Button>
        <Label Content="That's a button up there.." HorizontalAlignment="Center"/>
    </StackPanel>

Follow

Get every new post delivered to your Inbox.

Join 381 other followers