简体   繁体   English

自定义 WPF 上下文菜单

[英]Custom WPF context menu

I want to create a custom context menu that each item will have image on top and some text below it.我想创建一个自定义上下文菜单,每个项目的顶部都有图像,下面有一些文本。

I know i can achieve this with with manipulating the template like so我知道我可以通过像这样操作模板来实现这一点

<Style TargetType="{x:Type ContextMenu}">
    <Setter Property="Template">
      <Setter.Value>
           <ControlTemplate TargetType="{x:Type ContextMenu}">
                 //do whatever here
           </ControlTemplate>
       </Setter.Value>
     </Setter>
</<Style>

but i my program every control have same basic template that all of the control of the same type(here its contextmenu) inherit from it, and i dont want to ruin it by overriding the template here但是我的程序每个控件都有相同的基本模板,所有相同类型的控件(这里是它的上下文菜单)都继承自它,我不想通过在这里覆盖模板来破坏它

is there anyway i can achive waht i want without changing the template?无论如何我可以在不更改模板的情况下达到我想要的效果吗?

You need to set a key in your style.你需要在你的风格中设置一个key

<Style TargetType="{x:Type ContextMenu}" x:key="CustomContextMenu">
    <Setter Property="Template">
      <Setter.Value>
           <ControlTemplate TargetType="{x:Type ContextMenu}">
                 //do whatever here
           </ControlTemplate>
       </Setter.Value>
     </Setter>
</Style>

And apply it like this.并像这样应用它。

<Button Content="Right" Grid.Column="1">
    <Button.ContextMenu>
        <ContextMenu Style="{StaticResource CustomContextMenu}">
            <MenuItem Header="File" />
            <MenuItem Header="Save" />
            <MenuItem Header="SaveAs" />
        </ContextMenu>
    </Button.ContextMenu>
</Button>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM