Background color for MenuItem not changed on MouseOver

此生再无相见时 提交于 2019-12-13 17:15:13

问题


I have a Menu with three items and I'm trying to change the background color when the mouse hovers over any of the items. I've tried the IsMouseOver & IsHighlighted trigger property and neither works.

In my App.xaml:

<Style TargetType="MenuItem" x:Key="MenuItemStyle" >
        <Style.Triggers>
            <Trigger Property="MenuItem.IsHighlighted" Value="true">
                <Setter Property="Background" Value="Black"/>
            </Trigger>
        </Style.Triggers>          
    </Style>

In my Main.xaml:

<Menu HorizontalAlignment="Left" Height="30" VerticalAlignment="Top" Width="975
          " FontFamily="Tempus Sans ITC" FontSize="16"  >
        <Menu.Background>
            <LinearGradientBrush EndPoint="0.5,1" StartPoint="0.5,0">
                <GradientStop Color="#FFC8C8C8" Offset="0"/>
                <GradientStop Color="Black" Offset="1"/>
            </LinearGradientBrush>
        </Menu.Background>
        <Menu.Foreground>
            <SolidColorBrush Color="#FFFFFFFB"/>
        </Menu.Foreground>
        <MenuItem Header="New" Click="MenuNew_Click" VerticalAlignment="Center" Padding="15,4,8,3" Width="60">
            <MenuItem.ToolTip>
                <ToolTip>
                    Add new Park
                </ToolTip>
            </MenuItem.ToolTip>
        </MenuItem>
        <MenuItem Header="Search" Width="65" Padding="12,4,8,3"  >
            <MenuItem.ToolTip>
                <ToolTip> Select search option</ToolTip>
            </MenuItem.ToolTip>
            <MenuItem Header="Name" Background="Black" FontSize="14" Style="{StaticResource MenuItemStyle}" />
            <MenuItem Header="ID" Background="Black" FontSize="14"/>
            <MenuItem Header="OwnerName" Background="Black" FontSize="14"/>
        </MenuItem>          
    </Menu>    

回答1:


The default ControlTemplate for MenuItem (as extracted by Show Me The Template) doesn't set the MenuItem.Background property on mouse over, it sets an element in the template directly. Unfortunately, this means that you won't be able to just change the highlight color, but you'll have to recreate the entire ControlTemplate. MSDN has an example of how to do this (this one is from .NET 3.5 but should work for 4.0 or 4.5).

One other caveat in your code: since you're setting the Background directly on the MenuItems, your Style's Trigger would not work anyway. Because of DependencyProperty value precedence, the local value you set on the items can not be overridden by a Style Trigger.



来源:https://stackoverflow.com/questions/18194967/background-color-for-menuitem-not-changed-on-mouseover

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!