Windows Ribbon for WinForms, Part 11 – DropDownGallery, SplitButtonGallery and InRibbonGallery

27 באוקטובר 2009

In this post I'll show you how to use the different galleries available with the Windows Ribbon Framework.

The result of this post is a new sample named “09-Galleries” that you can find on the Windows Ribbon for WinForms project page. It looks like this:

image

image

Item Galleries vs. Command Galleries
The galleries that we will soon review comes in two flavors: item galleries and command galleries. In this section will see what’s the difference between these two.

Item Galleries

  • Gallery items are “simple” items, just text and image, similar to items in a ComboBox.
  • Items have an index and there is a concept of "Selected Item”.
  • Item galleries support preview. This means you get a “preview” notification (event) when you move over an item and also a “cancel preview” notification when you cancel the selection.
  • A single item in an item gallery has the following properties: Label, Image and Category ID.

Note: A ComboBox ribbon control is also an item gallery.

Command Galleries

  • Gallery items are actually commands.
  • The Commands are not indexed and thus doesn’t have the concept of “Selected Item”.
  • Command galleries doesn’t support preview.
  • A single item in a command gallery has the following properties: Command ID, Command Type and Category ID.

Note: Both gallery types have the concept of categories, see ComboBox post for more details.

Gallery Types
Now we will review the 3 gallery types we have, each one can be an item gallery or command gallery.
Note that according to MSDN a ComboBox is also considered to be a gallery which is always an item gallery. Since we already review the ComboBox in a previous post, I won’t mention it here.

DropDownGallery
Just a button that a click on it displays a list of items. The button itself has no action.
In the first image above, the leftmost control is a DropDownGallery.

SplitButtonGallery
Two buttons, one that is used as a default action and another one that opens a list of items.
In the second image above, the middle control is a SplitButtonGallery.

Note: We already saw in a previous post that the main difference between a DropDown and a SplitButton is that a SplitButton has a default item.

InRibbonGallery
The items are displayed inside the ribbon, no button is needed.
In the images above, the rightmost control is an InRibbonGallery.

Command Space
One additional feature you should know about, in the sake of completeness, is that all 3 galleries have a command space. This is a section on the bottom of the control that contains statically defined commands.
In the first image above, the DropDownGallery has a button defined in its command space.

Using Galleries
In the next sections I’ll show you how to define galleries in ribbon markup and use the new helper classes for easily operate on them. Note that since galleries have many options I will demonstrate only a representative subset.

Using DropDownGallery – Ribbon Markup
Here I’ll show you how to use the DropDownGallery as an item gallery with a command space.
Commands section:

<Application.Commands>
  <Command Name='cmdTabMain' Id='1000' LabelTitle='Main' />
  <Command Name='cmdGroupDropDownGallery' Id='1001' LabelTitle='Drop Down' />
  <Command Name='cmdDropDownGallery' Id='1002' LabelTitle='Size' >
    <Command.LargeImages>
      <Image>Res/Open32.bmp</Image>
    </Command.LargeImages>
    <Command.SmallImages>
      <Image>Res/Open16.bmp</Image>
    </Command.SmallImages>
  </Command>
  <Command Name='cmdCommandSpace' Id='1003' LabelTitle='Command Space' >
    <Command.LargeImages>
      <Image>Res/Save32.bmp</Image>
    </Command.LargeImages>
    <Command.SmallImages>
      <Image>Res/Save16.bmp</Image>
    </Command.SmallImages>
  </Command>
  …
</Application.Commands>

Views section:

<Application.Views>
  <Ribbon>
    <Ribbon.Tabs>
      <Tab CommandName='cmdTabMain'>
        <Group CommandName='cmdGroupDropDownGallery' SizeDefinition='OneButton'>
          <DropDownGallery CommandName='cmdDropDownGallery'
                           TextPosition='Hide'
                           Type='Items'>
            <DropDownGallery.MenuLayout>
              <FlowMenuLayout Columns='1' Rows='5' Gripper='None' />
            </DropDownGallery.MenuLayout>
            <DropDownGallery.MenuGroups>
              <MenuGroup>
                <Button CommandName='cmdCommandSpace' />
              </MenuGroup>
            </DropDownGallery.MenuGroups>
          </DropDownGallery>
        </Group>
        …
      </Tab>
    </Ribbon.Tabs>
  </Ribbon>
</Application.Views>

In the view part you define the use of a DropDownGallery along with its layout (how many columns and rows you want) and command space.
What makes this gallery an item gallery is setting the Type attribute to ‘Items’.
More details about DropDownGallery attributes can be found on MSDN.

Using DropDownGallery – Code Behind
Create an instance of RibbonLib.DropDownGallery helper class and register some of its events:

private Ribbon _ribbon = new Ribbon();
private RibbonDropDownGallery _dropDownGallery;

public Form1()
{
    InitializeComponent();

    _dropDownGallery = new RibbonDropDownGallery(_ribbon, (uint)RibbonMarkupCommands.cmdDropDownGallery);

    _dropDownGallery.OnExecute += new OnExecuteEventHandler(_dropDownGallery_OnExecute);
    _dropDownGallery.OnPreview += new OnPreviewEventHandler(_dropDownGallery_OnPreview);
    _dropDownGallery.OnCancelPreview += new OnCancelPreviewEventHandler(_dropDownGallery_OnCancelPreview);
}

void _dropDownGallery_OnCancelPreview(PropertyKeyRef key, PropVariantRef currentValue, IUISimplePropertySet commandExecutionProperties)
{
    Console.WriteLine("DropDownGallery::OnCancelPreview");
}

void _dropDownGallery_OnPreview(PropertyKeyRef key, PropVariantRef currentValue, IUISimplePropertySet commandExecutionProperties)
{
    Console.WriteLine("DropDownGallery::OnPreview");
}

void _dropDownGallery_OnExecute(PropertyKeyRef key, PropVariantRef currentValue, IUISimplePropertySet commandExecutionProperties)
{
    Console.WriteLine("DropDownGallery::OnExecute");
}

Add items to the DropDownGallery:

private void Form1_Load(object sender, EventArgs e)
{
    _ribbon.InitFramework(this);

    FillDropDownGallery();
}

private void FillDropDownGallery()
{
    // set label
    _dropDownGallery.Label = "Size";

    // set _dropDownGallery items
    IUICollection itemsSource = _dropDownGallery.ItemsSource;
    itemsSource.Clear();
    foreach (Image image in imageListLines.Images)
    {
        itemsSource.Add(new GalleryItemPropertySet()
                        {
                            ItemImage = _ribbon.ConvertToUIImage((Bitmap)image)
                        });
    
    }
}

Note that I’m using here a standard ImageList control to supply the bitmaps for the DropDownGallery.
GalleryItemPropertySet is a helper class that represents a single item in an item gallery.

Update (18.11.2009): The updated version of the Ribbon class provides an implementation for IUICommandHandler, so the user doesn't need to implement Execute and UpdateProperty methods anymore.

Finally, Connect IUICommandHandler.Execute and IUICommandHandler.UpdateProperty methods with the implementation of these methods in the DropDownGallery class:

public HRESULT Execute(uint commandId, UI_ExecutionVerb verb, ref PropertyKey key,
                       ref PropVariant currentValue,
                       IUISimplePropertySet commandExecutionProperties)
{
    if (commandId == (uint)RibbonMarkupCommands.cmdDropDownGallery)
    {
        return _dropDownGallery.Execute(verb, ref key, ref currentValue,
                                        commandExecutionProperties);
    }
    return HRESULT.S_OK;
}

public HRESULT UpdateProperty(uint commandId, ref PropertyKey key,
                              ref PropVariant currentValue, ref PropVariant newValue)
{
    if (commandId == (uint)RibbonMarkupCommands.cmdDropDownGallery)
    {
        return _dropDownGallery.UpdateProperty(ref key, ref currentValue, ref newValue);
    }
    return HRESULT.S_OK;
}

Using SplitButtonGallery – Ribbon Markup
Here I’ll show you how to use the SplitButtonGallery as a command gallery.
Commands section:

<Command Name='cmdGroupSplitButtonGallery' Id='1004' LabelTitle='Split Button' />
<Command Name='cmdSplitButtonGallery' Id='1005' LabelTitle='Brushes' >
  <Command.LargeImages>
    <Image>Res/Brush1.bmp</Image>
  </Command.LargeImages>
</Command>

Views section:


<Group CommandName="cmdGroupSplitButtonGallery" SizeDefinition="OneButton">
  <SplitButtonGallery CommandName="cmdSplitButtonGallery"
                      TextPosition="Hide" Type="Commands" HasLargeItems="true">
    <SplitButtonGallery.MenuLayout>
      <FlowMenuLayout Columns="4" Rows="3" Gripper="None"/>
    </SplitButtonGallery.MenuLayout>
  </SplitButtonGallery>
</Group>

In the view part you define the use of a SplitButtonGallery along with its layout (how many columns and rows you want), and optionally, a command space.
What makes this gallery a command gallery is setting the Type attribute to ‘Commands’.
More details about SplitButtonGallery attributes can be found on MSDN.

Using SplitButtonGallery – Code Behind
Create an instance of RibbonLib.SplitButtonGallery helper class.

private Ribbon _ribbon = new Ribbon();
private RibbonSplitButtonGallery _splitButtonGallery;
private RibbonButton[] _buttons;

public Form1()
{
    InitializeComponent();

    _splitButtonGallery = new RibbonSplitButtonGallery(_ribbon, (uint)RibbonMarkupCommands.cmdSplitButtonGallery);
}

Add items to the SplitButtonGallery:

private void Form1_Load(object sender, EventArgs e)
{
    _ribbon.InitFramework(this);

    FillSplitButtonGallery();
}

private void FillSplitButtonGallery()
{
    // set label
    _splitButtonGallery.Label = "Brushes";

    // prepare helper classes for commands
    _buttons = new RibbonButton[imageListBrushes.Images.Count];
    uint i;
    for (i = 0; i < _buttons.Length; ++i)
    {
        _buttons[i] = new RibbonButton(_ribbon, 2000 + i)
                          {
                              Label = "Label " + i.ToString(),
                              LargeImage = _ribbon.ConvertToUIImage((Bitmap) imageListBrushes.Images[(int) i])
                          };
    }

    // set _splitButtonGallery categories
    IUICollection categories = _splitButtonGallery.Categories;
    categories.Clear();
    categories.Add(new GalleryItemPropertySet() { Label = "Category 1", CategoryID = 1 });

    // set _splitButtonGallery items
    IUICollection itemsSource = _splitButtonGallery.ItemsSource;
    itemsSource.Clear();
    i = 0;
    foreach (Image image in imageListBrushes.Images)
    {
        itemsSource.Add(new GalleryCommandPropertySet()
                        {
                            CommandID = 2000 + i++,
                            CommandType = CommandType.Action,
                            CategoryID = 1
                        });
    }

    // add default item to items collection
    itemsSource.Add(new GalleryCommandPropertySet()
                    {
                        CommandID = (uint)RibbonMarkupCommands.cmdSplitButtonGallery,
                        CommandType = CommandType.Action,
                        CategoryID = 1
                    });
}

GalleryCommandPropertySet is a helper class that represents a single item in a command gallery.

Important: If you don’t add the default item to the items list of a SplitButtonGallery, the items will appears twice! This is probably a bug.

Update (18.11.2009): The updated version of the Ribbon class provides an implementation for IUICommandHandler, so the user doesn't need to implement Execute and UpdateProperty methods anymore.

Finally, Connect IUICommandHandler.Execute and IUICommandHandler.UpdateProperty methods with the implementation of these methods in the SplitButtonGallery and Button classes:

public HRESULT Execute(uint commandId, UI_ExecutionVerb verb, ref PropertyKey key,
                       ref PropVariant currentValue,
                       IUISimplePropertySet commandExecutionProperties)
{
    if (commandId == (uint)RibbonMarkupCommands.cmdSplitButtonGallery)
    {
        return _splitButtonGallery.Execute(verb, ref key, ref currentValue,
                                           commandExecutionProperties);
    }
    else if (commandId >= 2000)
    {
        return _buttons[commandId - 2000].Execute(verb, ref key, ref currentValue,
                                                  commandExecutionProperties);
    }
    return HRESULT.S_OK;
}

public HRESULT UpdateProperty(uint commandId, ref PropertyKey key,
                              ref PropVariant currentValue, ref PropVariant newValue)
{
    if (commandId == (uint)RibbonMarkupCommands.cmdSplitButtonGallery)
    {
        return _splitButtonGallery.UpdateProperty(ref key, ref currentValue,
                                                  ref newValue);
    }
    else if (commandId >= 2000)
    {
        return _buttons[commandId - 2000].UpdateProperty(ref key, ref currentValue,
                                                         ref newValue);
    }
    return HRESULT.S_OK;
}

 

Note the handling of dynamically added commands.

Using InRibbonGallery – Ribbon Markup
Here I’ll show you how to use the InRibbonGallery as an item gallery.
Commands section:

<Command Name='cmdGroupInRibbonGallery' Id='1006' LabelTitle='In Ribbon' />
<Command Name='cmdInRibbonGallery' Id='1007' />

Views section:


<Group CommandName="cmdGroupInRibbonGallery" SizeDefinition="OneInRibbonGallery">
  <InRibbonGallery CommandName="cmdInRibbonGallery" Type="Items"
                   MaxRows="3" MaxColumns="7">
  </InRibbonGallery>
</Group>

In the view part you define the use of a InRibbonGallery along with its layout. Note that InRibbonGallery has more control on how to layout its items.
More details about InRibbonGallery attributes can be found on MSDN.

Using InRibbonGallery – Code Behind
Similar to DropDownGallery code. This post is long enough.

That’s it for now,
Arik Poznanski.

kick it on DotNetKicks.com Shout it

הוסף תגובה
facebook linkedin twitter email

כתיבת תגובה

האימייל לא יוצג באתר. (*) שדות חובה מסומנים

4 תגובות

  1. Muhammad Adnan5 בדצמבר 2009 ב 12:27

    when i make installer for your galleries sample project which i got from windowsribbon.codeplex.com

    i get following error

    System.Runtime.InteropServices.COMException (0×80004005): Error HRESULT E_FAIL has been returned from a call to a COM component.
    at System.Runtime.InteropServices.Marshal.ThrowExceptionForHRInternal(Int32 errorCode, IntPtr errorInfo)
    at System.Runtime.InteropServices.Marshal.ThrowExceptionForHR(Int32 errorCode)
    at RibbonLib.Ribbon.InitFramework(IRibbonForm form, String resourceName, IntPtr hInstance)
    at RibbonLib.Ribbon.InitFramework(IRibbonForm form, String resourceName, Module resourceModule)
    at RibbonLib.Ribbon.InitFramework(IRibbonForm form)
    at _09_Galleries.Form1.Form1_Load(Object sender, EventArgs e)
    at System.Windows.Forms.Form.OnLoad(EventArgs e)
    at System.Windows.Forms.Form.OnCreateControl()
    at System.Windows.Forms.Control.CreateControl(Boolean fIgnoreVisible)
    at System.Windows.Forms.Control.CreateControl()
    at System.Windows.Forms.Control.WmShowWindow(Message& m)
    at System.Windows.Forms.Control.WndProc(Message& m)
    at System.Windows.Forms.ScrollableControl.WndProc(Message& m)
    at System.Windows.Forms.ContainerControl.WndProc(Message& m)
    at System.Windows.Forms.Form.WmShowWindow(Message& m)
    at System.Windows.Forms.Form.WndProc(Message& m)
    at System.Windows.Forms.Control.ControlNativeWindow.OnMessage(Message& m)
    at System.Windows.Forms.Control.ControlNativeWindow.WndProc(Message& m)
    at System.Windows.Forms.NativeWindow.Callback(IntPtr hWnd, Int32 msg, IntPtr wparam, IntPtr lparam)

    i have win 7 sdk… i was just wondering.. when i deploy this in xp or win2k based machine… how it would work.. i mean what exactly dll/references are required for ribbon…

    להגיב
  2. arik5 בדצמבר 2009 ב 13:06

    The Windows Ribbon Framework (provided by Microsoft) is available only on Vista (with latest updates) and Windows 7.
    It is not available on Windows XP / Windows 2000.

    Since the Windows Ribbon for WinForms is just a wrapper around this feature, it has all the limitation of windows ribbon framework.

    להגיב
  3. Mo19 ביוני 2010 ב 23:42

    Hello Arik,

    I'm trying to get the CommandID from the OnExecute delegate but all three parameters are null.

    How can I get the CommandID from an event?

    להגיב
  4. arik23 ביוני 2010 ב 17:12

    Mo, can you be more specific, what are you trying to do?
    The OnExecute delegate is attached to a specific command, so you should know it, since you have set it..

    להגיב