如何在组件之间共享 ContextMenu

How can I share a ContextMenu between Components

我有一个 WPF 应用程序,它在许多地方使用相同的菜单组件。因此,我希望我的菜单是一个单独的组件,我可以在需要的地方以某种方式调用它。截至目前,我的菜单视图逻辑看起来是这样的。

<TreeView.ContextMenu>
    <ContextMenu DataContext="{Binding Path=PlacementTarget.Tag,RelativeSource={RelativeSource Self}}">
        <MenuItem Header="Open" Command="{Binding MenuDelegateCommand}"
                  IsEnabled="{Binding Path=OpenEnabled}"
                  CommandParameter="{Binding RelativeSource={RelativeSource Self}, Path=Header}" />
        <Separator />
        <MenuItem Header="Blah Attributes">
        <MenuItem Header="Properties" Command="{Binding MenuDelegateCommand}"
                                  IsEnabled="{Binding Path=OpenEnabled}"
                                  CommandParameter="{Binding RelativeSource={RelativeSource Self}, Path=Header}" />
......

到目前为止,我已经尝试将 ContextMenu 部分分解成它自己的 class,就像这样

<UserControl>
 <Grid>
   <ContextMenu>

但是 ContextMenu 与 Visual Tree 的交互方式不同,所以这是不行的。我想到了其他东西,但在模板、数据模板和装饰器之间我迷路了。

非常感谢任何帮助。

您可能正在寻找静态资源。使您的 ContextMenu 成为顶级元素内的资源(或在单独的资源文件中,然后包括 ResourceDictionary):

<!-- Use whatever control you want here, or a separate resources
     file if you want to share across controls                   -->
<Window.Resources>
  <ContextMenu x:Key="MyMenu" DataContext="{Binding Path=PlacementTarget.Tag,RelativeSource={RelativeSource Self}}">
        <MenuItem Header="Open" Command="{Binding MenuDelegateCommand}"
                  IsEnabled="{Binding Path=OpenEnabled}"
                  CommandParameter="{Binding RelativeSource={RelativeSource Self}, Path=Header}" />
        <Separator />
        <MenuItem Header="Blah Attributes">
        <MenuItem Header="Properties" Command="{Binding MenuDelegateCommand}"
                  IsEnabled="{Binding Path=OpenEnabled}"
                  CommandParameter="{Binding RelativeSource={RelativeSource Self}, Path=Header}" />
  </ContextMenu>
......
</Window.Resources>

稍后再参考上下文菜单:

<TreeView ContextMenu="{StaticResource MyMenu}" />