Telerik UI for Windows Phone by Progress

This topic will demonstrate an approach that allows one instance of RadContextMenu to be reused across a whole application. this can be achieved by putting a small menu provider object that has a Menu property in the app's resources. Then every UIElement across the app can use the same context menu by binding the ContextMenu attached property to this menu provider.

Creating the menu provider

Creating the menu provider is very simple. We just need a simple class with one property and then we insert an instance of this class into the application's resources:

CopyC#
public class RadContextMenuProvider
{
    public RadContextMenu Menu
    {
        get;
        set;
    }
}
CopyC#
/// <summary>
/// Constructor for the Application object.
/// </summary>
public App()
{
    // Global handler for uncaught exceptions. 
    UnhandledException += Application_UnhandledException;

    // Initialize global menu provider.
    RadContextMenuProvider menuProvider = new RadContextMenuProvider();
    menuProvider.Menu = this.CreateContextMenu();

    this.Resources.Add("MenuProvider", menuProvider);

    // Standard Silverlight initialization
    InitializeComponent();


    // Phone-specific initialization
    InitializePhoneApplication();
}

private RadContextMenu CreateContextMenu()
{
    RadContextMenu result = new RadContextMenu();

    result.Items.Add(new RadContextMenuItem() { Content = "Option 1" });
    result.Items.Add(new RadContextMenuItem() { Content = "Option 2" });
    result.Items.Add(new RadContextMenuItem() { Content = "Option 3" });

    return result;
}

Finally we just bind to this menu provider from any of our pages:

CopyXAML
<Grid x:Name="LayoutRoot">
    <ListBox telerikPrimitives:RadContextMenu.ContextMenu="{Binding Path=Menu, Source={StaticResource MenuProvider}}"
             x:Name="listBox"/>
</Grid>
CopyC#
public partial class MainPage : PhoneApplicationPage
{
    public MainPage()
    {
        InitializeComponent();
        this.listBox.ItemsSource = this.Generatedata();

        RadContextMenu.SetFocusedElementType(this.listBox, typeof(ListBoxItem));
    }

    IEnumerable Generatedata()
    {
        for (int i = 0; i < 100; ++i)
        {
            yield return "DataItem " + (i + 1).ToString();
        }
    }

    private void OnMenuOpening(object sender, ContextMenuOpeningEventArgs e)
    {
        ListBoxItem focusedItem = e.FocusedElement as ListBoxItem;
        if (focusedItem == null)
        {
            // We don't want to open the menu if the focused element is not a list box item.
            // If the list box is empty focusedItem will be null.
            e.Cancel = true;
            return;
        }
    }
}