コンテキストメニュー(ContextMenu)は、コントロールをマウスで右クリックした時にポップアップするメニューを表示させる機能です。
ここではその方法について解説します。
UI要素にコンテキストメニューを追加
FrameworkElement クラスは ContextMenu というプロパティを持っています。
この ContextMenu を使ってメニューを作成していきます。
ボタンやラベルなど、ほとんどの UI 要素は FrameworkElement クラスを継承しているのでコンテキストメニューを使う事が出来ます。
<Window x:Class="WpfTest1.TestWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:local="clr-namespace:WpfTest1"
mc:Ignorable="d"
Title="TestWindow" Height="300" Width="300">
<WrapPanel>
<Button Content="ボタン" Margin="20" Width="100" Height="30">
<Button.ContextMenu>
<ContextMenu>
<MenuItem Header="メニュー1"/>
<MenuItem Header="メニュー2"/>
<MenuItem Header="メニュー3"/>
<MenuItem Header="メニュー4"/>
</ContextMenu>
</Button.ContextMenu>
</Button>
</WrapPanel>
</Window>
<ContextMenu>要素の中身は通常のメニューと同じです。
親要素に追加すれば子要素にも
コンテキストメニューを親要素に追加すれば、全ての子要素でコンテキストメニューが有効になります。
<Window x:Class="WpfTest1.TestWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:local="clr-namespace:WpfTest1"
mc:Ignorable="d"
Title="TestWindow" Height="300" Width="300">
<Window.ContextMenu>
<ContextMenu>
<MenuItem Header="メニュー1"/>
<MenuItem Header="メニュー2"/>
<MenuItem Header="メニュー3"/>
<MenuItem Header="メニュー4"/>
</ContextMenu>
</Window.ContextMenu>
<WrapPanel>
<Button Content="ボタン" Margin="20" Width="100" Height="30"/>
<Button Content="ボタン" Margin="20" Width="100" Height="30"/>
</WrapPanel>
</Window>


コメント
コメントを投稿