WPF

WPF コンテキストメニューを作ってみよう!

2012年12月9日

今回は簡単なコンテキストメニューを実装してみます。
WPF の コンテキストメニューは FrameworkElement のプロパティですので Button、RadioButton、CheckBox、TextBlock などのコントロールで利用できます。

実装方法はコントロールの ContextMenu クラスに MenuItem を割り当てます。
ここでは Style を使ってコンテキストメニューを用意していますが、コントロールに直接定義することもできます。

<Grid>
<Grid.Resources>
<!-- コンテキストメニュー -->
<Style TargetType="Button">
<Setter Property="ContextMenu">
<Setter.Value>
<ContextMenu>
<MenuItem Header="1"/>
<MenuItem Header="2"/>
<MenuItem Header="3"/>
</ContextMenu>
</Setter.Value>
</Setter>
</Style>
</Grid.Resources>
<Button Content="Button"
Name="button1"
Height="23"
Width="75">
<!-- これでもいけます -->
<!--<Button.ContextMenu>
<ContextMenu>
<MenuItem Header="item1"/>
<MenuItem Header="item2"/>
<MenuItem Header="item3"/>
</ContextMenu>
</Button.ContextMenu>-->
</Button>
</Grid>

FrameworkElement の派生クラスはこちら↓

FrameworkElement 階層
http://msdn.microsoft.com/ja-jp/library/ms602719%28v=vs.80%29.aspx

-WPF