如何:创建共享的 ContextMenu

更新:2007 年 11 月

您可以通过将 ContextMenu 定义为资源并将控件的 ContextMenu 属性设置为 ContextMenu 的引用,来使多个控件共享 ContextMenu。您可以通过设置 x:Shared 属性属性,来指定控件是共享同一个 ContextMenu,还是每个控件都有自己的 ContextMenu

示例

下面的示例将 ContextMenu 创建为一项资源,并为四个控件指定引用。 该示例将 ContextMenux:Shared 属性设置为 true,以便四个控件共享同一个 ContextMenu 实例。 您可以通过选中一个控件的 ContextMenu 中的第一个 MenuItem 并确认在其他控件的 ContextMenu 中也选中了该 MenuItem 来对此进行验证。

<ContextMenu x:Key="SharedInstanceContextMenu" x:Shared="True">
  <MenuItem Header="This MenuItem is checkable" IsCheckable="True" />
  <Separator/>
  <MenuItem Header="This is a regular MenuItem" />
</ContextMenu>


...


<Button Margin="0,5,0,0" Background="LightBlue"
    Content="This Button has a ContextMenu"
    ContextMenu="{DynamicResource SharedInstanceContextMenu}" />
<Button Background="Pink"
    Content="This Button has the same ContextMenu"
    ContextMenu="{DynamicResource SharedInstanceContextMenu}" />
<CheckBox BorderBrush="Red"
    Content="This Check Box has the same ContextMenu"
    ContextMenu="{DynamicResource SharedInstanceContextMenu}" />
<CheckBox BorderBrush="Green" 
    Content="This Check Box has the same ContextMenu"
    ContextMenu="{DynamicResource SharedInstanceContextMenu}" />

下面的示例将 ContextMenu 创建为一项资源,并为四个控件指定引用。 此示例将 ContextMenux:Shared 属性 设置为 false,以便对每个控件使用一个新的 ContextMenu 实例。 您可以通过选中一个控件的 ContextMenu 中的第一个 MenuItem 并确认在其他控件的 ContextMenu 中未选中该 MenuItem 来对此进行验证。

<ContextMenu x:Key="NonsharedInstanceContextMenu" x:Shared="False">
  <MenuItem Header="This MenuItem is checkable" IsCheckable="true" />
  <Separator/>
  <MenuItem Header="This is a regular MenuItem" />
</ContextMenu>


...


<Button Background="LightBlue" Margin="0,5,0,0"
    Content="This Button has a ContextMenu"
    ContextMenu="{DynamicResource NonsharedInstanceContextMenu}" />
<Button Background="Pink"
    Content="This Button has the same ContextMenu"
    ContextMenu="{DynamicResource NonsharedInstanceContextMenu}" />
<CheckBox BorderBrush="Red"
    Content="This Check Box has the same ContextMenu"
    ContextMenu="{DynamicResource NonsharedInstanceContextMenu}" />
<CheckBox BorderBrush="Green" 
    Content="This Check Box has the same ContextMenu"
    ContextMenu="{DynamicResource NonsharedInstanceContextMenu}" />

有关完整示例,请参见 控件共享的 ContextMenu 的示例

请参见

任务

如何:在已禁用的控件上启用 ContextMenu

概念

ContextMenu 概述

参考

Menu

MenuItem