Infragistics(R) NetAdvantage(R) Windows Phone 2012.2
Binding ContextMenu to Data
E-mail your feedback on this topic.

Glossary Item Box

Topic Overview

Purpose

This topic explains how to bind ContextMenu™ to a list of custom objects.

Required background

The following topics are prerequisites to understanding this topic:

Type

Content

Concepts

  • Data Binding

Topics

Topic

Purpose

This topic provides an overview of the ContextMenu control and its features.

This topic explains with a code example how to add the ContextMenu to a page in both XAML and the code-behind.


 


In this topic


Binding to Data Sources – Conceptual Overview

Binding to data sources summary

The ContextMenu inherits from the ItemsControl class, therefore, as with any other ItemsControl, when adding items to the menu, any of the following approaches can be used:

1. Adding MenuItem objects to the collection set as the Items property of the context menu

2. Adding custom objects to the collection set as the Items  property of the context menu

3. Setting the ItemsSource property to a collection implementing the IEnumerable interface.

No matter which of the last two approaches you choose, what actually happens is that a MenuItem is auto-generated for each object that you add to either the Items property or in the IEnumerable object. By default, for each of these objects the ToString() method is called and the result is displayed in a TextBlock in each of the MenuItems. In order to control what exactly is displayed, you can either override the ToString method of your custom classes to return the desired value, or define a DataTemplate and set it as the ItemTemplate of the ContextMenu.

This topic explains in detail how to use the third approach of data binding and how to use the ItemTemplate property to apply a custom data template.

Note: Setting the DisplayMemberPath property of the ContextMenu does not change the behavior of the menu when displaying items.

Steps

Following are the general conceptual steps for Binding ContextMenu to data.

1. Creating a list of custom objects
2. Setting the data context of the context menu (the DataContext property)
3. Binding the menu to the data context (the ItemsSource property to the DataContext property)
4. Configuring the look of the context menu (setting the ItemTemplate property of ContextMenu to an appropriate DataTemplate)

Binding ContextMenu to a List of Objects – Procedure

Introduction

The procedure below explains how to use a list of custom objects as items in a context menu. This is approach listed under #3 in the Binding to data sources summary block.

You will notice in the example code that the ContextMenu control has its Height property set. Though not required, is highly recommended that you always explicitly specify a value for this property in order for the menu to render correctly.

Preview

The following screenshot is a preview of the final result.

Prerequisites

To complete the procedure, you need the following:

  • A MS Visual Studio® Windows Phone application project with an application page created
  • A visual element (e.g. a Rectangle object) to the main grid container in the page
  • A ContextMenu control added to the visual element. (This can be achieved by performing the first step of the procedure in the Adding ContextMenu topic.)

Overview

Following is a conceptual overview of the process:

1. Creating a list of custom objects
2. Setting the data context of the context menu
3. Binding the menu to the data context
4. Configuring the look of the context menu

Steps

Step

Description

1. Create a list of custom objects. 1. Define a custom class.

For the sake of example, this procedure uses a simple class with two string properties.

Add the class definition to either a new C# / Visual Basic file or to the code-behind of your page.

In C#:

public class CustomItem
{
    public string Caption { get; set; }
    public string Description { get; set; }
}

In Visual Basic:

Public Class CustomItem
      Public Property Caption As String
      Public Property Description As String
End Class
2. Create and fill a list of objects of the custom class.

In the constructor of the page, initialize a list of CustomItem objects and add a few items to it:

In C#:

var customItems = new List<CustomItem>();
customItems.Add(new CustomItem() { Caption = "Item 1", Description = "Description 1" });
customItems.Add(new CustomItem() { Caption = "Item 2", Description = "Description 2" });
customItems.Add(new CustomItem() { Caption = "Item 3", Description = "Description 3" });

In Visual Basic:

Dim customItems = New List(Of CustomItem)()
customItems.Add(New CustomItem() With { .Caption = "Item 1", .Description = "Description 1" })
customItems.Add(New CustomItem() With { .Caption = “Item 2", .Description = "Description 2" })
customItems.Add(New CustomItem() With { .Caption = "Item 3", .Description = "Description 3" })
2. Set the data context of the context menu.

Set the list created in the step 1 as the DataContext of the context menu. Assuming that the x:Name property of the menu is set to “contextMenu”, the code is the following:

In C#:

contextMenu.DataContext = customItems;

In Visual Basic:

contextMenu.DataContext = customItems
3. Bind the menu to the data context.

Bind the ItemsSource property of the context menu to its data context:

In XAML:

ItemsSource=”{Binding}”

In C#:

contextMenu.SetBinding(ContextMenu.ItemsSourceProperty, new Binding());

In Visual Basic:

contextMenu.SetBinding(ContextMenu.ItemsSourceProperty, New Binding())
Note: The exact implementation of steps 2 and 3 may vary. For example, you could declare the list as a property of your page and then bind the ItemsSource of the menu to it.
4. Configure the look of the context menu.

In this step, you specify a particular look for the context menu by setting the ItemTemplate property of ContextMenu to an appropriate DataTemplate.

The ItemTemplate  property defines how the custom objects from the ItemsSource will be rendered. For the CustomItem class, a suitable DataTemplate that can be used as ItemTemplate is the following:

In XAML:

<ig:ContextMenu.ItemTemplate>
    <DataTemplate>
        <StackPanel>
            <TextBlock Text="{Binding Caption}"/>
            <TextBlock Text="{Binding Description}" 
                       Foreground="{StaticResource PhoneAccentBrush}"
                       FontSize="{StaticResource PhoneFontSizeSmall}"/>
        </StackPanel>
    </DataTemplate>
</ig:ContextMenu.ItemTemplate>

Code

In XAML:

<phone:PhoneApplicationPage 
    x:Class="ContextMenuPlayground.Page3"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:phone="clr-namespace:Microsoft.Phone.Controls;assembly=Microsoft.Phone"
    xmlns:shell="clr-namespace:Microsoft.Phone.Shell;assembly=Microsoft.Phone"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    xmlns:ig="clr-namespace:Infragistics.Toolkit.Controls.Menus;assembly=InfragisticsWP7.Controls.Toolkit.v12.2"
    FontFamily="{StaticResource PhoneFontFamilyNormal}"
    FontSize="{StaticResource PhoneFontSizeNormal}"
    Foreground="{StaticResource PhoneForegroundBrush}"
    SupportedOrientations="Portrait" Orientation="Portrait"
    mc:Ignorable="d" d:DesignHeight="768" d:DesignWidth="480"
    shell:SystemTray.IsVisible="True">
    <Grid x:Name="LayoutRoot" Background="Transparent">
        <Grid.RowDefinitions>
            <RowDefinition Height="Auto"/>
            <RowDefinition Height="*"/>
        </Grid.RowDefinitions>
        <!--TitlePanel contains the name of the application and page title-->
        <StackPanel x:Name="TitlePanel" Grid.Row="0" Margin="12,17,0,28">
            <TextBlock x:Name="ApplicationTitle" Text="MY APPLICATION" Style="{StaticResource PhoneTextNormalStyle}"/>
            <TextBlock x:Name="PageTitle" Text="page name" Margin="9,-7,0,0" Style="{StaticResource PhoneTextTitle1Style}"/>
        </StackPanel>
        <Grid x:Name="ContentPanel" Grid.Row="1" Margin="12,0,12,0">
            <Rectangle x:Name="rectangle" Width="200" Height="200"
                       VerticalAlignment="Top" Fill="{StaticResource PhoneAccentBrush}">
                <ig:ContextMenuManager.ContextMenu>
                    <ig:ContextMenu x:Name="contextMenu" ItemsSource=”{Binding}” Height="300">
                        <ig:ContextMenu.ItemTemplate>
                            <DataTemplate>
                                <StackPanel>
                                    <TextBlock Text="{Binding Caption}"/>
                                    <TextBlock Text="{Binding Description}" 
                                               Foreground="{StaticResource PhoneAccentBrush}"
                                               FontSize="{StaticResource PhoneFontSizeSmall}"/>
                                </StackPanel>
                            </DataTemplate>
                        </ig:ContextMenu.ItemTemplate>
                    </ig:ContextMenu>
                </ig:ContextMenuManager.ContextMenu>
            </Rectangle>
        </Grid>
    </Grid>
</phone:PhoneApplicationPage>

In C#:

using System.Collections.Generic;
using System.Windows.Data;
using Infragistics.Toolkit.Controls.Menus;
using Microsoft.Phone.Controls;
namespace ContextMenuPlayground
{
    public partial class Page3 : PhoneApplicationPage
    {
        public Page3()
        {
            InitializeComponent();
            var customItems = new List<CustomItem>();
            customItems.Add(new CustomItem() { Caption = "Item 1", Description = "Description 1" });
            customItems.Add(new CustomItem() { Caption = "Item 2", Description = "Description 2" });
            customItems.Add(new CustomItem() { Caption = "Item 3", Description = "Description 3" });
            contextMenu.DataContext = customItems;
        }
    }
}

In Visual Basic:

Imports System.Collections.Generic
Imports System.Windows.Data
Imports Infragistics.Toolkit.Controls.Menus
Imports Microsoft.Phone.Controls
Namespace ContextMenuPlayground
      Public Partial Class Page3
            Inherits PhoneApplicationPage
            Public Sub New()
                  InitializeComponent()
                  Dim customItems = New List(Of CustomItem)()
                  customItems.Add(New CustomItem() With { _
                        Key .Caption = "Item 1", _
                        Key .Description = "Description 1" _
                  })
                  customItems.Add(New CustomItem() With { _
                        Key .Caption = "Item 2", _
                        Key .Description = "Description 2" _
                  })
                  customItems.Add(New CustomItem() With { _
                        Key .Caption = "Item 3", _
                        Key .Description = "Description 3" _
                  })
                  contextMenu.DataContext = customItems
            End Sub
      End Class
End Namespace

Related Content

Topics

The following topics provide additional information related to this topic.

Topic

Purpose

This topic explains, code examples, how to bind the context menu items to commands so that when the user taps on an item, the respective command is executed.


Samples

The following samples provide additional information related to this topic.

Sample

Purpose

Data Binding

Bind ContextMenu to a list of items


Resources

The following material (available outside the Infragistics® family of content) provides additional information related to this topic.

Title

Purpose

MSDN article about data binding.