【WPF】コンテキストメニューの表示方法
WPFでコンテキストメニューを表示する方法。
▽▼完成図▼▽
①Buttonコントロールにコンテキストメニューを設定して表示
②<Window.ContextMenu>でコンテキストメニューを設定して表示
③ボタン以外のコントロールでコンテキストメニューを表示
▽▼ソースコード▼▽
■MainWindow.xaml
<Window x:Class="MyWorkProject.Views.MainWindow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:prism="http://prismlibrary.com/" prism:ViewModelLocator.AutoWireViewModel="True" Title="{Binding Title}" Height="350" Width="525"> <!--②--> <Window.ContextMenu> <ContextMenu> <MenuItem Header="共通コンテキストメニュー"/> </ContextMenu> </Window.ContextMenu> <Grid> <StackPanel> <!--①--> <Button Content="ボタン"> <Button.ContextMenu> <ContextMenu> <MenuItem Header="ボタン子"/> </ContextMenu> </Button.ContextMenu> </Button> <!--②--> <Button Content="ボタン(共通)"/> <!--③--> <Label Content="ラベル"/> <TextBlock Text="テキストブロック"/> <TextBlock Text="テキストブロック"/> <TextBox Text="テキストボックス"/> <ContentControl prism:RegionManager.RegionName="ContentRegion" /> </StackPanel> </Grid> </Window>
☆<Window.ContextMenu>を設定すると、コンテキストメニューを個別設定した箇所(上記だと「ボタン」)以外で右クリックして
☆コンテキストメニューは、ボタン以外にも設定できる。