更新 : 2007 年 11 月
ここでは、TabControl を作成し、ContextMenu を各 TabItem に割り当てる方法について説明します。ユーザーが ContextMenu の項目をクリックすると、TabItem は Click イベントを処理する必要があります。ハンドラは、ContextMenu 項目に追加できますが、実行する適切なアクションの ContextMenu 項目の対象が何であるかを認識している必要があります。
その方法を次の例に示します。最初の例では、TabItem を作成し、ContextMenu を TabItem に割り当てます。
使用例
<TabItem Name="backgroundcolor" Header="Choose a Background Color">
<TabItem.ContextMenu>
<ContextMenu MenuItem.Click="MyMenuHandler">
<MenuItem Header="Red" Name="red"/>
<MenuItem Header="Blue" Name="blue"/>
<MenuItem Header="Yellow" Name="yellow"/>
</ContextMenu>
</TabItem.ContextMenu>
<TabItem.Content>Some content about background colors.</TabItem.Content>
</TabItem>
2 番目の例ではハンドラに Click イベント呼び出しを処理させる方法を示します。
void MyMenuHandler(object sender, RoutedEventArgs e)
{
ContextMenu cm = (ContextMenu)sender;
target = cm.PlacementTarget;
if(e.Source==red)
{
backgroundcolor.Background = Brushes.Red;
backgroundcolor.Header = "Background red";
}
else if(e.Source==blue)
{
backgroundcolor.Background = Brushes.LightBlue;
backgroundcolor.Header = "Background blue";
}
else if(e.Source==yellow)
{
backgroundcolor.Background = Brushes.Yellow;
backgroundcolor.Header = "Background yellow";
}
}
ContextMenu の対象を検索するには、前の例または次の例のコードを使用できることに注目してください。
ContextMenu cm = (ContextMenu)ContextMenu.ItemsControlFromItemContainer ((MenuItem)e.OriginalSource);
UIElement placementTarget = cm.PlacementTarget;