Toolbars

Using Toolbars in a Xamarin.Mac application

PDF for offline use
Sample Code:
Related Articles:
Related SDKs:

Let us know how you feel about this

Translation Quality


0/250

last updated: 2017-03

This article covers working with Toolbars in a Xamarin.Mac application. It covers creating and maintaining Toolbars in Xcode and Interface builder, how to expose the Toolbar Items to code using Outlets and Actions, enabling and disabling Toolbar Items and finally responding to Toolbar Items in C# code.

Contents

This article will cover the following topics in detail:

Overview

When working with C# and .NET in a Xamarin.Mac application, you have access to the same Toolbar that a developer working in in Objective-C and Xcode does. Because Xamarin.Mac integrates directly with Xcode, you can use Xcode's Interface Builder to create and maintain your Toolbar Items (or optionally create them directly in C# code).

macOS Toolbars can be added to the top edge of a Window and provide easy access to commands for the functionality of the window. Toolbars can be hidden, shown or customized by the end user of the application and may represent items as either a small or large icon with text or just text only.

An example toolbar

In this article, we'll cover the basics of working with Toolbars and Toolbar Items in a Xamarin.Mac application. It is highly suggested that you work through the Hello, Mac article first, specifically the Introduction to Xcode and Interface Builder and Outlets and Actions sections, as it covers key concepts and techniques that we'll be using in this article.

You may want to take a look at the Exposing C# classes / methods to Objective-C section of the Xamarin.Mac Internals document as well, it explains the Register and Export commands used to wire-up your C# classes to Objective-C objects and UI Elements.

Introduction to Toolbars

Any window in a macOS application can have a Toolbar placed on it that will take over the top section of the content area and become a part of the title bar:

An example window with toolbar

Toolbars provide any easy way for the end user of your application to quickly access the most important or most used features. For example, a document editing application might have toolbar items to quickly set the color or font of selected text and a shortcut to print the document.

Toolbars have three ways of displaying items that they contain:

  1. Icon and Text
    Toolbar with icons and text
  2. Icon Only
    An icon only toolbar
  3. Text Only
    A text only toolbar

The end user can switch between these modes by right-clicking the Toolbar and selecting a new display mode from a contextual menu:

The toolbar configuration menu

From the same menu they can choose to display the Toolbar in a smaller size:

Small toolbar icons

Or they have they option of customizing the Toolbar:

Customizing a toolbar

As the developer, when you are designing the Toolbar in Xcode's Interface Builder, you have the option of providing extra Items that are not part of the default Toolbar and allow the end user to add and remove items at will. The user also has the option of quickly return the Toolbar to it's default configuration.

The Toolbar will automatically wire-up to the default View menu and provide the ability for the user to hide and show the Toolbar as well as customize it:

The View menu

See our Built-In Menu Functionality documentation for more details.

Additionally, any modifications to the appearance or content of the Toolbar will automatically be maintained between runs (based on setting selected in Interface Builder), without any extra coding required on the developer's part.

In the next sections, we'll look at creating and maintaining Toolbars in Xcode's Interface Builder, then we'll look at responding to those items in code.

Setting a Custom Main Window Controller

To be able to create Outlets and Actions to expose UI elements to C# code, the Xamarin.Mac app will need to be using a Custom Window Controller.

Do the following:

  1. Open the app's Storyboard in Xcode's Interface Builder.
  2. Select the NSWindowController in the Design Surface.
  3. Switch to the Identity Inspector view and enter WindowController as the Class Name:
    Setting the class name
  4. Save your changes and return to Xamarin Studio to sync.
  5. A WindowController.cs file will be added to your Project in the Solution Explorer in Xamarin Studio:
    Selecting the Window Controller
  6. Reopen the Storyboard in Xcode's Interface Builder.
  7. The WindowController.h file will be available for use:
    The WindowController.h file

Creating and Maintaining Toolbars in Xcode

As stated above, Toolbars are a part of a macOS application's window so you'll created and maintain them with Xcode's Interface builder. To get started, double-click the Main.storyboard file under the application's project in the Solution Explorer:

Selecting the main storyboard

This will open the Window for edit in Xcode. In the Library Inspector, enter tool in the Search Box to make it easier to find all of the Toolbar UI elements:

The Library Inspector

Drag a Toolbar onto the Window in the Interface Editor. With the Toolbar on the window and selected, you'll have a few properties you can set to control it's behavior in the Attribute Inspector:

The Attribute Inspector

The following properties are available:

  1. Display - This controls the Toolbar's display mode such as Icons and Text, Icon Only, etc.
  2. Visible at Launch - If selected, the Toolbar is visible by default.
  3. Customizable - If selected, the end user can edit and customize the Toolbar.
  4. Separator - If selected, a thin separator line is drawn between the window's contents and the bottom of the Toolbar.
  5. Size - Sets the view size of the Toolbar.
  6. Autosave - If selected, the Toolbar will automatically save and changes made by the end user without the developer having to write any code.

Let's go ahead an select the Autosave option for our toolbar and leave all the other properties at the default settings.

If we open the Toolbar in the Interface Hierarchy and select an item, the Customize dialog is displayed in the Interface Editor:

Customizing the toolbar

From here we can set the properties of items that are already a part of the Toolbar, add extra items that the end user can use to customize the Toolbar (that are not shown by default) and design the default Toolbar for our application. To add items to the Toolbar, drag them from the Library Inspector:

The Library Inspector

We have the following Toolbar items that we can add:

  • Image Toolbar Item - Allows use the use a bitmap image that has been added to the Resources folder (with a Build Action of Bundle Resource) as an icon.
  • Flexible Space Toolbar Item - Provides a flexible space to justify the following Toolbar Items. For example: one or more Toolbar Items followed by a Flexible Space Toolbar Item and another Toolbar Item would pin the last item to the right side of the Toolbar.
  • Space Toolbar Item - Provides a fixed space between items on the Toolbar.
  • Separator Toolbar Item - Provides a visible separator between two or more Toolbar Items and allow you to visible group them.
  • Customize Toolbar Item - Provides a shortcut to allow the user to customize the Toolbar.
  • Print Toolbar Item - Provides a shortcut to allow the user to print the document in the window.
  • Show Colors Toolbar Item - Displays the standard system Color Picker:
    The Color Selector
  • Show Font Toolbar Item - Displays the standard system Font Dialog:
    The font selector

Note: You are not limited to placing these items alone on the Toolbar. As we will see later, many of the standard Cocoa UI controls (such as the Search Field, Segment Control or Horizontal Slider) can also be added to a Toolbar.

Adding an Item to a Toolbar

To add an item to a Toolbar, open the Toolbar in the Interface Hierarchy and select an item, the Customize dialog is displayed in the Interface Editor. Next, drag a new item from the Library Inspector onto the Allowed Toolbar Items area:

The allowed toolbar items

If you want to new item to be part of the default Toolbar, drag the new item down to the Default Toolbar Items area:

Dragging a toolbar item

From here you can reorder the items on the default Toolbar by dragging left or right. Next set the default properties for the item from the Attribute Inspector:

Customizing a toolbar item

You have the following options:

  • Image Name - Select an image from the Resources folder (that has a Build Action of Bundle Resource) as an icon for the item.
  • Label - This is the text that will be displayed for the item when it is on the Toolbar.
  • Palette Label - This is the text for the item in the Allowed Toolbar Items area.
  • Tag - Is a unique Identifier that can optionally set by the developer to help identify the item in code.
  • Identifier - Defines the item as one of the built-in types (Color, Font, Print, etc.) If you provide a custom Identifier, you can use it to select a given Toolbar Item from code.
  • Selectable - If checked, the item will act like an on/off button.

Note: You can add an item to the Allowed Toolbar Items area and not add it to the Default Toolbar so that the end user can later customize the toolbar and add it themselves. In this way, you can provide the ability for the user to customize your application to better fit their specific needs and target a much larger audience.

Adding Other UI Controls to a Toolbar

As stated above, you are not limited to the Toolbar Items when adding elements to a Toolbar. Several of the other Cocoa UI elements (such as Search Field and Segment Control) can be added to a Toolbar.

To add an item to a Toolbar, open the Toolbar in the Interface Hierarchy and select an item, the Customize dialog is displayed in the Interface Editor. Next, drag a Search Field from the Library Inspector onto the Allowed Toolbar Items area:

Customizing a toolbar

From here you can configure the UI item as normal in Xcode and expose it as an Action or Outlet.

Now that we have the basics on working with Toolbars in Xcode out of the way, let's look at working with Toolbars in Xamarin.Mac.

Built-in Toolbar Item Support

As with Cocoa Menus, several of the other Cocoa UI elements have built in support for the standard Toolbar Items. For example, if we drag a Text View into our window, position it to fill the content area of the window:

Selecting a Text View from the Library

Then save our changes, return to Xamarin Studio and sync with Xcode, run the application, enter some text, select it and click the Color Toolbar Item, the functionality is automatically wired-up and the selected text will change the color that we pick in the Color Picker:

An example of built in toolbar functionality

Using Images with Toolbar Items

Using the Image Toolbar Item any bitmap image added to the Resources folder (and given a Build Action of Bundle Resource) can be displayed on the Toolbar as an icon.

Let's do the following:

  1. In Xamarin Studio in the Solution Explorer, right-click the Resources folder and select Add > Add Files.
  2. From the Add Files dialog box, navigate to your desired images, select them and click the Open button:
    Adding an image
  3. Select Copy, Use the same action for all selected files and click the OK button:
    Setting the copy action
  4. In the Solution Explorer, double-click the MainWindow.xib file to open it for editing in Xcode.
  5. Open the Toolbar in the Interface Hierarchy and select an item, the Customize dialog is displayed in the Interface Editor.
  6. Drag an Image Toolbar Item from the Library Inspector and drop it on the Toolbar under the Allowed Toolbar Items area:
    Selecting a toolbar item
  7. In the Attribute Inspector, select the image we just added in Xamarin Studio:
    Setting the item image
  8. Set the Label to Trash and the Palette Label to Erase Document:
    Setting the item label
  9. Drag a Separator Toolbar Item from the Library Inspector and drop it on the Toolbar under the Allowed Toolbar Items area:
    Adding a separator
  10. Finally, drag the Separator and the Image Toolbar Item down into the Default Toolbar Items area and drag to reposition them as follows:
    The default toolbar items
  11. Save your changes and return to Xamarin Studio to sync with Xcode.

If we run the application, our new Toolbar Item will be displayed by default:

An example toolbar run

Exposing Toolbar Items with Outlets and Actions

As with any UI element, to access a Toolbar or Toolbar Item it must be attached to an Outlet or Action before it can be accessed in C# code.

To expose a Toolbar Item to code, do the following:

  1. In the Solution Explorer, double-click the Main.storyboard file to open it for editing in Xcode.
  2. First, ensure that the custom class WindowController has been assigned to the main Window Controller in the Identity Inspector:
    The Identity Inspector
  3. Next, select the Toolbar Item in the Interface Hierarchy:
    Selecting the toolbar item
  4. Open the Assistant View and select the WindowController.h file then control-drag from the Toolbar Item to the WindowController.h file.
  5. Set the Connection type to Action, enter trashDocument for the Name and click the Connect button:
    Configuring the Action
  6. Expose the Text View as an Outlet called documentEditor in the ViewController.h file:
    Configuring the Outlet
  7. Save your changes and return to Xamarin Studio to sync with Xcode.

In Xamarin Studio, edit the ViewController.cs file and add the following code:

#region Public Methods
public void EraseDocument() {
    documentEditor.Value = "";
}
#endregion

Next, edit the WindowController.cs file and add the following code to the bottom of the WindowController class:

[Export ("trashDocument:")]
void TrashDocument (NSObject sender) {

    var controller = ContentViewController as ViewController;
    controller.EraseDocument ();
}

If we run the application, the Trash Toolbar Item will be active:

An example app run

If we enter some text and click the Trash icon, the text will be deleted.

Disabling Toolbar Items

To disable an item on a Toolbar, you first need to create a custom instance of NSToobarItem and override the Validate method. Next you assign the custom type to the item that you want to enable/disable in Interface Builder.

To create our custom NSToolbarItem class, let's right-click on the project and select Add > New File... to open the New File dialog box. Then, select General > Empty Class, enter ActivatableItem for the Name and click the New button:

Adding an empty class

Next, edit the ActivatableItem.cs file and make it look like the following:

using System;

using Foundation;
using AppKit;

namespace MacToolbar
{
    [Register("ActivatableItem")]
    public class ActivatableItem : NSToolbarItem
    {
        public bool Active { get; set;} = true;

        public ActivatableItem ()
        {
        }

        public ActivatableItem (IntPtr handle) : base (handle)
        {
        }

        public ActivatableItem (NSObjectFlag  t) : base (t)
        {
        }

        public ActivatableItem (string title) : base (title)
        {
        }

        public override void Validate ()
        {
            base.Validate ();

            Enabled = Active;
        }
    }
}

Double-click the Main.storyboard file to open it for editing in Xcode. Select the Trash Toolbar Item (that we created above) and change its class to ActivatableItem in the Identity Inspector:

Setting the class name

Now create an Outlet for the Trash Toolbar Item called trashItem. Save your changes and return to Xamarin Studio to sync with Xcode. Finally, edit the MainWindow.cs file and make the AwakeFromNib method look like the following:

public override void AwakeFromNib ()
{
    base.AwakeFromNib ();

    // Disable trash
    trashItem.Active = false;
}

Now if we run the application, the Trash item will be disabled in the Toolbar even though we have a listener attached to it's Action:

An example app run

Summary

This article has taken a detailed look at working with Toolbars and Toolbar Items in a Xamarin.Mac application. We saw how to create and maintain Toolbars in Xcode's Interface Builder, how some UI Controls automatically work with Toolbar Items, how to work with Toolbars in C# code and how to enable and disable items.

Xamarin Workbook

If it's not already installed, install the Xamarin Workbooks app first. The workbook file should download automatically, but if it doesn't, just click to start the workbook download manually.