如何在 WPF Menu 控件上设置前景色和背景色?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13783705/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-08 23:36:11  来源:igfitidea点击:

How to set foreground and background colors on a WPF Menu control?

wpfmenumenuitemstyling

提问by RickNZ

I've been working in WPF for quite a while, but there's something basic about styling that I just don't get.

我已经在 WPF 中工作了很长一段时间,但有一些关于样式的基本知识,我只是不明白。

How can I set the foreground and background colors for a Menucontrol? I started with this:

如何设置Menu控件的前景色和背景色?我从这个开始:

    <Menu IsMainMenu="True" Background="#FF3A3A3A" Foreground="White">
        <MenuItem Header="_File">
            <MenuItem Header="_Exit">
            </MenuItem>
        </MenuItem>
    </Menu>

The foreground color is apparently inherited by the MenuItem, but the background is not. Next attempt:

前景色显然是由 继承的MenuItem,但背景不是。下一次尝试:

    <Menu IsMainMenu="True" Background="#FF3A3A3A" Foreground="White">
        <MenuItem Background="#FF3A3A3A" Header="_File">
            <MenuItem Header="_Exit">
            </MenuItem>
        </MenuItem>
    </Menu>

Now the highlight/overlay colors aren't right when the menu is activated, and I don't see an obvious property to set them. In addition, the menu popup has a wide, white border, and I don't see how to change it's color (or size), either.

现在,激活菜单时突出显示/叠加颜色不正确,并且我没有看到设置它们的明显属性。此外,菜单弹出窗口有一个宽的白色边框,我也不知道如何更改它的颜色(或大小)。

What am I missing?

我错过了什么?

回答by Thraka

You will want to learn more about templates and styles in WPF (XAML really). In XAML, how a control looks and how a control operates are two completely different things. In your example, you may have a Foreground and Background property, but the style\template of the control my not utilize these properties for the display of the control.

您将想要了解有关 WPF(实际上是 XAML)中的模板和样式的更多信息。在 XAML 中,控件的外观和控件的运行方式是完全不同的两件事。在您的示例中,您可能有一个 Foreground 和 Background 属性,但控件的样式\模板可能不会利用这些属性来显示控件。

Read http://wpftutorial.net/Templates.htmland http://wpftutorial.net/TemplatesStyles.html, they will give you a good and quick overview. For a more in depth look, read this: http://msdn.microsoft.com/en-us/library/ee230084.aspx

阅读http://wpftutorial.net/Templates.htmlhttp://wpftutorial.net/TemplatesStyles.html,它们会给你一个很好的快速概览。如需更深入的了解,请阅读:http: //msdn.microsoft.com/en-us/library/ee230084.aspx

If you are using Visual Studio 2012 to edit your WPF UI, you can easily create a copy of the style\template the menu control is using, and then edit it. If you are using Visual Studio 2010, you should download and install (it may or may not be free) Expression Blend to edit your XAML UI.

如果您使用 Visual Studio 2012 来编辑 WPF UI,则可以轻松创建菜单控件正在使用的样式\模板的副本,然后对其进行编辑。如果您使用的是 Visual Studio 2010,您应该下载并安装(它可能是免费的,也可能不是)Expression Blend 来编辑您的 XAML UI。

Tip: If you are using Visual Studio 2012, make sure your Document Outlinewindow pane is visible all the time. This is very handy for editing a XAML UI. Mine defaulted to being collapsed on the left side of the program. This pane is visible in Expression Blend by default.

提示:如果您使用的是 Visual Studio 2012,请确保您的文档大纲窗口窗格始终可见。这对于编辑 XAML UI 非常方便。我的默认折叠在程序的左侧。默认情况下,此窗格在 Expression Blend 中可见。

Find the MenuItem control in the Document Outline. Right-click on it and select Edit Template->Edit a Copy...

在文档大纲中找到 MenuItem 控件。右键单击它并选择编辑模板-> 编辑副本...

This will create a copy of the existing look-and-feel of the menu item for you to edit. When you do this, you will be in editing mode of that template, to "pop out" of that mode, click on the little icon on the top left of the Document Outline window.

这将创建菜单项现有外观的副本供您编辑。执行此操作时,您将处于该模板的编辑模式,要“弹出”该模式,请单击“文档大纲”窗口左上角的小图标。

Return Scope Button

返回范围按钮

When editing the template, you can see the layout and design of the template. When a menu item is being as the drop-down part, it's really displayed like a Popup menu (right click menu). Looking through that template, what pops out at me right away is this color resource named SubMenuBackgroundBrush:

编辑模板时,可以看到模板的布局和设计。当菜单项作为下拉部分时,它实际上显示为一个弹出菜单(右键菜单)。翻阅那个模板,我立刻想到的是这个名为 SubMenuBackgroundBrush 的颜色资源:

<SolidColorBrush x:Key="SubMenuBackgroundBrush" Color="#FFF5F5F5"/>

If you do a search for SubMenuBackgroundBrush you can see that it is used on a part named PART_Popup:

如果您搜索 SubMenuBackgroundBrush,您可以看到它用于名为 PART_Popup 的部件:

<Popup x:Name="PART_Popup" AllowsTransparency="true" Focusable="false" HorizontalOffset="1" IsOpen="{Binding IsSubmenuOpen, RelativeSource={RelativeSource TemplatedParent}}" PopupAnimation="{DynamicResource {x:Static SystemParameters.MenuPopupAnimationKey}}" Placement="Bottom" VerticalOffset="-1">
    <Themes:SystemDropShadowChrome x:Name="Shdw" Color="Transparent">
        <Border x:Name="SubMenuBorder" BorderBrush="#FF959595" BorderThickness="1" Background="{StaticResource SubMenuBackgroundBrush}">
            <ScrollViewer x:Name="SubMenuScrollViewer" Margin="1,0" Style="{DynamicResource {ComponentResourceKey ResourceId=MenuScrollViewer, TypeInTargetAssembly={x:Type FrameworkElement}}}">
                <Grid RenderOptions.ClearTypeHint="Enabled">
                    <Canvas HorizontalAlignment="Left" Height="0" VerticalAlignment="Top" Width="0">
                        <Rectangle x:Name="OpaqueRect" Fill="{StaticResource SubMenuBackgroundBrush}" Height="{Binding ActualHeight, ElementName=SubMenuBorder}" Width="{Binding ActualWidth, ElementName=SubMenuBorder}"/>
                    </Canvas>
                    <Rectangle Fill="#F1F1F1" HorizontalAlignment="Left" Margin="1,2" RadiusY="2" RadiusX="2" Width="28"/>
                    <Rectangle Fill="#E2E3E3" HorizontalAlignment="Left" Margin="29,2,0,2" Width="1"/>
                    <Rectangle Fill="White" HorizontalAlignment="Left" Margin="30,2,0,2" Width="1"/>
                    <ItemsPresenter x:Name="ItemsPresenter" KeyboardNavigation.DirectionalNavigation="Cycle" Grid.IsSharedSizeScope="true" Margin="2" SnapsToDevicePixels="{TemplateBinding SnapsToDevicePixels}" KeyboardNavigation.TabNavigation="Cycle"/>
                </Grid>
            </ScrollViewer>
        </Border>
    </Themes:SystemDropShadowChrome>
</Popup>

This is the popup that you see when you right-click on something that shows a menu, or a dropdown menu. Change the references from: {StaticResource SubMenuBackgroundBrush}to {TemplateBinding Foreground}.

这是当您右键单击显示菜单或下拉菜单的内容时看到的弹出窗口。将引用从: 更改{StaticResource SubMenuBackgroundBrush}{TemplateBinding Foreground}

When you run the program, you'll see that the main background of the popup has changed, but the area where the icon is displayed has not. These are all the <Rectangle Fill="items in the popup control too. Change those also. The last reference to Rectangle looks like its the line splitting the icon and the text, you may not what to change that.

当你运行程序时,你会看到弹出窗口的主背景发生了变化,但显示图标的区域没有。这些也是<Rectangle Fill="弹出控件中的所有项目。改变那些也。对 Rectangle 的最后一个引用看起来像是分割图标和文本的线,您可能无法更改它。

Enjoy the wonderful world of templates. It looks confusing and like a lot of work. It is. But when you get the hang of it, it's a very coolsystem. It's hard to go back to any other UI system after you get the hang of it.

享受美妙的模板世界。它看起来令人困惑,并且需要做很多工作。这是。但是当你掌握了它的窍门时,它是一个非常酷的系统。掌握了窍门后,很难再回到任何其他 UI 系统。

回答by McGarnagle

What am I missing?

我错过了什么?

Controls are more or less customizable, and there are two levels of customizing a control:

控件或多或少是可自定义的,自定义控件有两个级别:

  1. Setting properties like Foreground, Background, etc, in the XAML where you place the control.
  2. Setting the Templatein your Stylefor the control, and creating your own ControlTemplate.
  1. 设置属性,如ForegroundBackground等,在XAML您放置控制。
  2. 设置Template在你Style的控制,并创建自己的ControlTemplate

The second is more involved, but it offers much more flexibility in making the control look how you want. If this case, it sounds like that's what you'll need. Check out the default ControlTemplate for Menu and MenuItem. You can copy/paste them and modify as needed.

第二个涉及更多,但它提供了更大的灵活性,可以使控件看起来像您想要的那样。如果是这种情况,听起来这就是您所需要的。查看Menu 和 MenuItem默认 ControlTemplate。您可以复制/粘贴它们并根据需要进行修改。

<Window.Resources>
    <Style TargetType="{x:Type Menu}">
        <Setter Property="Template">
            <ControlTemplate TargetType="{x:Type Menu}">
                <!-- your modified template here -->
            </ControlTemplate>
        </Setter>
    </Style>
    <Style TargetType="{x:Type MenuItem}">
        <Setter Property="Template">
            <ControlTemplate TargetType="{x:Type MenuItem}">
                <!-- your modified template here -->
            </ControlTemplate>
        </Setter>
    </Style>
</Window.Resources>