ContextMenu
is an expanding menu control that is displayed when a host FrameworkElement
is tapped and held. A ContextMenu
can be added to any FrameworkElement
using the ContextMenuService.ContextMenu
attached property. The following excerpt shows a Button
that has a context menu assigned to it, displaying three menu items:
<Button Margin="0,12" VerticalAlignment="Center" Padding="16"
Content="Using Click Events">
<toolkit:ContextMenuService.ContextMenu>
<toolkit:ContextMenu>
<toolkit:MenuItem
Header="option 1"
Click="MenuItem_Click"/>
<toolkit:MenuItem
Header="option 2"
Click="MenuItem_Click"/>
<toolkit:MenuItem
Header="option 3"
Click="MenuItem_Click"/>
</toolkit:ContextMenu>
</toolkit:ContextMenuService.ContextMenu>
</Button>
When the button is tapped and held, the page content is zoomed out and the list of menu items is displayed (see Figure 9.9).
In this example the event handler for each MenuItem.Click
event is the same. The handler retrieves the Header
text of the selected MenuItem
and displays it in a TextBlock
, like so:
void MenuItem_Click(object sender, RoutedEventArgs e)
{
TextBlock_LastSelectedMenuItem.Text = (string)((MenuItem)sender).Header;
}
By default, when shown, the ContextMenu
reduces the scale of all other elements on the page, giving the context menu center stage. Internally the ContextMenu
does this by creating a WritableBitmap
containing an image of the page. A ScaleTransform
is then applied to the WritableBitmap
, which is placed above the page content but below ContextMenu
host. This is a nice little trick, used often in the Toolkit. One downside of this approach, however, and one that you may become more aware of as you find yourself progressing with the ContextMenu
, is that the snapshot taken of the page content captures buttons in their pressed state, which may or may not be what you want. Notice, in Figure 9.9, that the background of the button is white, which interferes with the highlighting of the menu items.
To prevent the background from being scaled when the context menu is shown, set the ContextMenu.IsZoomEnabled
property to false, as shown:
<Button Margin="0,12" VerticalAlignment="Center" Padding="16"
Content="Using IsZoomEnabled=false">
<toolkit:ContextMenuService.ContextMenu>
<toolkit:ContextMenu IsZoomEnabled="false">
<toolkit:MenuItem Header="option 1" Click="MenuItem_Click"/>
<toolkit:MenuItem Header="option 2" Click="MenuItem_Click"/>
<toolkit:MenuItem Header="option 3" Click="MenuItem_Click"/>
</toolkit:ContextMenu>
</toolkit:ContextMenuService.ContextMenu>
</Button>
With IsZoomEnabled
set to false, an image of the page content is not used, and the actual page elements are displayed and continue to show animation. Consequently, a button control is able to transition out of its pressed state when the menu is shown (see Figure 9.10).
3.145.91.206