So far you have seen the ContextMenu
employed with hardwired MenuItems
and Click
events. This approach is adequate for simple apps. Yet, the MenuItem
class supports ICommands
out of the box. And, with this, you can bind a viewmodel’s ICommand
to a MenuItem
, removing the need for Click
event handlers in the code-beside.
To demonstrate, we bind a viewmodel command to a MenuItem
, which displays a message to the user. The ContextMenuViewModel
class, in the downloadable sample code, contains a ShowMessageCommand
property, declared as shown:
readonly DelegateCommand showMessageCommand;
public ICommand ShowMessageCommand
{
get
{
return showMessageCommand;
}
}
The task of the ShowMessageCommand
is to display a message using the custom IMessageService
. For more information regarding the ImessageService
, see Chapter 2, “Fundamental Concepts in Windows Phone Development.” The ShowMessageCommand
is initialized within the viewmodel’s constructor. When the command executes, it presents the command parameter using the message service, as shown in the following excerpt:
public ContextMenuViewModel()
{
showMessageCommand = new DelegateCommand(
parameter =>
{
var messageService = Dependency.Resolve<IMessageService>();
messageService.ShowMessage(parameter + " clicked!");
});
/* Content omitted. */
}
As with most examples in this book, the viewmodel is initialized and assigned to the view’s DataContext
property like so:
public ContextMenuView()
{
InitializeComponent();
DataContext = new ContextMenuViewModel();
}
With the viewmodel and command in place, MenuItems
are able to bind to the command in the view XAML. In the following excerpt you see three MenuItem
controls, each bound to the ShowMessageCommand
. The first uses a string as its command parameter. The second and third use the RelativeSource
markup extension to bind to their own Header
properties. See the following excerpt:
<Button Margin="0,12" VerticalAlignment="Center" Padding="16"
Content="Using ICommands">
<toolkit:ContextMenuService.ContextMenu>
<toolkit:ContextMenu>
<toolkit:MenuItem
Header="option 1"
Command="{Binding ShowMessageCommand}"
CommandParameter="option 1" />
...
</toolkit:ContextMenu>
</toolkit:ContextMenuService.ContextMenu>
</Button>
When a MenuItem
is tapped, a message box is displayed with the MenuItem
’s Header
(see Figure 9.11).
18.118.37.120