Menu Close

WP7 ContextMenu: answers to popular questions

by WindowsPhoneGeek

In the last few days we received lots of questions about how to use ContextMenu in WP7. In this mini tutorial we will give our answers to some of them.

NOTE: Before we begin let me first mention that ContextMenu is a part of the Silverlight for Windows Phone 7 toolkit. You can also take a look at our WP7 ContextMenu in depth | Part1: key concepts and API article for reference.

Question 1: Can I add Context Menu to DataTemplate ?

Question 2: I have ListBox with ContextMenu. How can I highlight the ListBox SelectedItem?

Question 3: I have ListBox with ContextMenu. How to get  a reference to the ListBox tapped item from the ContextMenu Click handler?

[…]

WP7 ContextMenu in depth | Part1: key concepts and API

I am starting a “WP7 ContextMenu in depth” series of articles in which I am going to talk about the Windows Phone 7 ContextMenu  in details. In this article “Part1: key concepts and API”  I will talk about the key properties, events and the main features of the Windows Phone 7 Context Menu control in details.

One of the new components in the Silverlight Toolkit is ContextMenu. Basically when the user taps and holds on any item the context menu appears. It is used in areas like for example the application list, where if you tap and hold an application you get the option to pin it to the start menu, uninstall, etc.

To begin using ContextMenu first  add a reference to  the Microsoft.Phone.Controls.Toolkit.dll  assembly which is installed with the toolkit and you can find it in :
C:\Program Files (x86)\Microsoft SDKs\Windows Phone\v7.0\Toolkit\Nov10\Bin\Microsoft.Phone.Controls.Toolkit.dll.

You will also need to add the “toolkit” prefix declaration. Make sure that your page declaration includes the “toolkit” namespace:

xmlns:toolkit="clr-namespace:Microsoft.Phone.Controls;assembly=Microsoft.Phone.Controls.Toolkit"

38menu2_2[1] 

The sample code should looks like:

<toolkit:ContextMenuService.ContextMenu>
    <toolkit:ContextMenu>
        <toolkit:MenuItem Header="Item1"/>
        <toolkit:MenuItem Header="Item2"/>
        <toolkit:MenuItem Header="Item3"/>
        <toolkit:MenuItem Header="Item4"/>
        <toolkit:MenuItem Header="Item5"/>
    </toolkit:ContextMenu>
</toolkit:ContextMenuService.ContextMenu>

ContextMenuService

ContextMenuService provides the system implementation for displaying a ContextMenu. Basically it consists of a “ContextMenu” attached dependency property.

  • ContextMenu

Identifies the ContextMenu attached property.

       Example:

<toolkit:ContextMenuService.ContextMenu>
 <toolkit:ContextMenu>
 ...
 <toolkit:ContextMenu>
 <toolkit:ContextMenuService.ContextMenu>

 

ContextMenu

Key Properties

  • IsOpen

IsOpen is a dependency property of type bool. It gets or sets a value indicating whether the ContextMenu is visible.

  • IsZoomEnabled

IsZoomEnabled is a dependency property of type bool.  It gets or sets a value indicating whether the background will zoom out when the ContextMenu is open.

       Example:

<toolkit:ContextMenu VerticalOffset="100.0" IsZoomEnabled="True"  x:Name="menu">
</toolkit:ContextMenu >
  • ItemContainerStyle

ItemContainerStyle is a dependency property of type Style .It gets or sets the Style that is applied to the container element generated for each item.

       Example:

                   <toolkit:ContextMenu   x:Name="databoundMenu"> 
                        <toolkit:ContextMenu.ItemContainerStyle> 
                            <Style TargetType="toolkit:MenuItem"> 
                              <Setter Property="Background" Value="YellowGreen" /> 
                              <Setter Property="Margin" Value="5" /> 
                            </Style> 
                        </toolkit:ContextMenu.ItemContainerStyle> 
                    </toolkit:ContextMenu>
  • VerticalOffset

VerticalOffset is a dependency property of type double. It gets or sets the vertical distance between the target origin and the popup alignment point.

       Example:

                   <toolkit:ContextMenu VerticalOffset="100.0" IsZoomEnabled="True"  x:Name="menu">
                   </toolkit:ContextMenu >

Events

  • Closed

Closed occurs when a particular instance of a ContextMenu closes.

       Example:

       this.menu.Closed += new RoutedEventHandler(menu_Closed);
       void menu_Closed(object sender, RoutedEventArgs e) 
        { //add some content here}
  • Opened

Opened occurs when a particular instance of a ContextMenu opens.

       Example:

       this.menu.Opened += new RoutedEventHandler(menu_Opened);
       void menu_Opened(object sender, RoutedEventArgs e) 
        { //add some content here}

 

MenuItem

Key Properties

  • Command

Command is a dependency property of type ICommand. It gets or sets the command associated with the menu item.

  • CommandParameter

CommandParameter is a dependency property of type object.  It gets or sets the parameter to pass to the Command property of a MenuItem.

  • Header

Header  is a dependency property of type  object.  It gets or sets the item that labels the control. The default value is null.

  • HeaderTemplate

HeaderTemplate is a dependency property of type DataTemplate. It gets or sets a data template that is used to display the contents of the control’s header.

  • ItemContainerStyle

ItemContainerStyle is a dependency property of type Style .It gets or sets the Style that is applied to the container element generated for each item.

Events

  • Click

Click occurs when a MenuItem is clicked.

       Example:

       <toolkit:MenuItem Header="Add"  Click="MenuItem_Click"/>
       private void MenuItem_Click(object sender, RoutedEventArgs e) 
        {//add some content here}

 

 

Populating ContextMenu with Items

Here is an example of how to use this control in the easiest way using MenuItems:

<Button Content="OpenContextMenu" Height="100" Width="270">
    <toolkit:ContextMenuService.ContextMenu>
        <toolkit:ContextMenu>
            <toolkit:MenuItem Header="Add"  Click="MenuItem_Click"/>
            <toolkit:MenuItem Header="Update"  Click="MenuItem_Click"/>
            <toolkit:MenuItem Header="Delete"  Click="MenuItem_Click"/>
        </toolkit:ContextMenu>
    </toolkit:ContextMenuService.ContextMenu>
</Button>
private void MenuItem_Click(object sender, RoutedEventArgs e)
{
    MenuItem menuItem = (MenuItem)sender;
    MessageBox.Show("You chose to  " + menuItem.Header.ToString(),"Result",MessageBoxButton.OK);
}

The result can be seen on the following screen shots:

      

In this example when the user tap and hold the “OpenContextMenu” button as a result a context menu appears from where you can select from three options. After you choose an item a MessageBox appears with information about the selected operation.

DataBinding ContextMenu

Here is an example of how to populate ContextMenu using simple data binding. We will also add some ItemContainerStyle in order to change the background color of the items:

 
<Button Content="DataBinding" Height="100" Width="270">
    <toolkit:ContextMenuService.ContextMenu>
        <toolkit:ContextMenu   x:Name="databoundMenu">
            <toolkit:ContextMenu.ItemContainerStyle>
                <Style TargetType="toolkit:MenuItem">
                  <Setter Property="Background" Value="YellowGreen" />
                  <Setter Property="Margin" Value="5" />
                </Style>
            </toolkit:ContextMenu.ItemContainerStyle>
        </toolkit:ContextMenu>
    </toolkit:ContextMenuService.ContextMenu>
</Button>
List<string> menuItems = new List<string>() {"Copy", "Paste", "Cut" };
this.databoundMenu.ItemsSource = menuItems;

The result can be seen on the following screen shots:

   

That was all about the key properties, events and the main features of the Windows Phone 7 ContextMenu in depth.

I hope that the article was helpful. You can find the full source code here:

Ferie quasi finite :(

Manca poco ormai.. abbiamo appena fatto l’ultimo bagno in piscina.. e domani si torna a casa 🙁

E’ stato davvero bello, a parte qualche rara rogna (vedi chiavetta internet e alcuni episodi a venezia) posso dire che è stata un vacanza fantastica 😛

Ora bisogna tornare al mondo reale.. e per le prossime ferie se ne parla il prossimo anno.. sarà lunga aspettare!! 

Ora bisogna rimettere i neuroni in carreggiata e ripartire a tutto gas! 🙂

abbronzatura :D

E’ forte, perchè sto sotto l’ombrellone da 2 giorni sempre costantemente all’ombra, eppure riesco a scottarmi come non mai.. è incredibile!
In compenso bubu può andare ai provini della pubblicità dei ringo! XD

Che bello stare qui.. il tempo poi ci sta aiutando, riesce ad esserci il sole anche quando piove 😛

Ferieeee!

Che bello il dolce far niente 🙂
Niente obblighi, niente forzature, puoi mangiare quando vuoi, dormire quando vuoi, andare in spiaggia o in piscina… mmmm ci piace XD

Peccato che so che non durerà a lungo, ma vedo di sfruttare questi giorni più che posso per rilassarmi e stare insieme alla mia dolce metà XD

Sono soddifazioni :)

From: Microsoft <wmcomm@e-mail.microsoft.com>
Date: 2011/8/4
Subject: Message to ‘Top 200’ registered developers

We’re contacting you because you publish one of the amazing top 200 applications on Windows Phone. You’ve built an experience that is in high demand with our consumers. You play a key role in kick starting the Windows Phone developer ecosystem. We want to continue this journey together.

Aria di cambiamenti

A forza di pensarci poi alla fine finisci per cascarci dentro..
Ancora nulla di certo, ma sicuramente il cambiamento sarebbe importante se la cosa va in porto.
Ora però è inutile stare tanto a spippolarmi su questi cose.. domani cominciano ufficilamente le ferie, e l’unica cosa che devo fare è godermele 🙂

Se ne riparlerà quando torno, tanto è ancora tutto da vedere, tutto da decidere.

Scelte..

E’ strano quando ricevi una proposta allettante (leggasi stipendio piu del doppio di quello attuale) ma non sai se accettare o meno.. sarà che sono troppo razionale, sarà che mi piace quello che faccio adesso.. però ovviamente è impossibile non pensarci.. 

C’è un fattore determinante però.. se cambiassi lavoro andrei a finire definitivamente dove a volte sono attualmente.. cioè continuare imperterrito lavori fino alle 3 di notte solo per il semplice fatto che non mi rendo conto di che ore sono!

Quando mi prendo via male vado avanti ad oltranza senza badare tanto al resto, ed fortunamente per ora succede solo ogni tanto.. se dovessi cambiare lavoro probabilmente succederebbe tutti i giorni, e non è quello che voglio.

La sfiga ci vede benissimo!

Risatona

Ok.. la sfiga ci vede sicuramente benissimo.. la scheda madre che ho ordinato nuova a quanto pare è totalmente morta.. di conseguenza niente firewall hardware per ora.. intanto però sono riuscito a riconfigurare il router in modo da poter avere il sito online.. era ora Risatona

Adesso aspetto solo sabato per andare in ferie.. ne ho proprio bisogno! Fico

Finalmente!

Risatona

Dopo tanta fatica sono riuscito a reindirizzare windows home server 2011 da una sottodirectory, in modo da avere come principale questo sito. Risatona

Ora manca solo da configurare il nuovo hardware per IPCop e poi il sito va in linea Fico