Q063. WPF でショートカットメニューを表示するには?

A. ContextMenu を使用します。


以下、Livet を使った簡単なサンプルです。TextBox に ContextMenu を設け、右クリックでポップアップを表示、選択したメニューを TextBox に表示します。


まず ViewModel です。ViewModel のコード量は多そうに見えますが、Livet が提供するスニペットを使ってるため、ほとんどコーディングせず実装してます。

Public Class MainWindowViewModel
	Inherits ViewModel

#Region "MessageText変更通知プロパティ"
	Private _MessageText As String

	Public Property MessageText() As String
		Get
			Return _MessageText
		End Get
		Set(ByVal value As String)
			If (_MessageText = value) Then Return
			_MessageText = value
			RaisePropertyChanged("MessageText")
		End Set
	End Property
#End Region

#Region "MorningCommand"
	Private _MorningCommand As ViewModelCommand

	Public ReadOnly Property MorningCommand() As ViewModelCommand
		Get
			If _MorningCommand Is Nothing Then
				_MorningCommand = New ViewModelCommand(AddressOf Morning)
			End If
			Return _MorningCommand
		End Get
	End Property

	Private Sub Morning()
		Me.MessageText = "おはよう"
	End Sub
#End Region

#Region "HelloCommand"
	Private _HelloCommand As ViewModelCommand

	Public ReadOnly Property HelloCommand() As ViewModelCommand
		Get
			If _HelloCommand Is Nothing Then
				_HelloCommand = New ViewModelCommand(AddressOf Hello)
			End If
			Return _HelloCommand
		End Get
	End Property

	Private Sub Hello()
		Me.MessageText = "こんにちは"
	End Sub
#End Region

#Region "EveningCommand"
	Private _EveningCommand As ViewModelCommand

	Public ReadOnly Property EveningCommand() As ViewModelCommand
		Get
			If _EveningCommand Is Nothing Then
				_EveningCommand = New ViewModelCommand(AddressOf Evening)
			End If
			Return _EveningCommand
		End Get
	End Property

	Private Sub Evening()
		Me.MessageText = "こんばんは"
	End Sub
#End Region

End Class


View です。MenuItem には ViewModel で定義したコマンドをバインドしています。

<Window xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
	xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
	xmlns:i="http://schemas.microsoft.com/expression/2010/interactivity"
	xmlns:ei="http://schemas.microsoft.com/expression/2010/interactions"
	xmlns:l="http://schemas.livet-mvvm.net/2011/wpf"
	xmlns:local="clr-namespace:ContextMenuSample"
	xmlns:d="http://schemas.microsoft.com/expression/blend/2008" 
	xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" 
	mc:Ignorable="d" x:Class="MainWindow"
	Title="MainWindow" Height="100" Width="180">
	
	<Window.DataContext>
		<local:MainWindowViewModel />
	</Window.DataContext>
	
	<Grid>
		<TextBox Margin="0,20" IsReadOnly="True" Text="{Binding MessageText}" >
			<TextBox.ContextMenu>
				<ContextMenu>
					<MenuItem Header="おはよう"   Command="{Binding MorningCommand}" />
					<MenuItem Header="こんにちは" Command="{Binding HelloCommand}"/>
					<Separator />
					<MenuItem Header="こんばんは" Command="{Binding EveningCommand}" />
				</ContextMenu>
			</TextBox.ContextMenu>
		</TextBox>
	</Grid>
</Window>


WPF FAQ の目次に戻る