cravie
cravie

Reputation: 35

WPF/MVVM Alternate background color of menuitems

I've looked and tried to figure this out myself but I've been stuck on this for a while now, and I was wondering if its possible to alternate the background color of a menuitem in WPF? I've tried alternatecount on the menuitems and tried to change the background color based off of that, but nothing happens. I know I could hardcode the background color of the menuitems but my menu's are dynamic and change as I'm using an MVVM pattern to bind them. If anyone knows how to do this, any help would be appreciated.

Thanks

Upvotes: 1

Views: 222

Answers (1)

Xiaoy312
Xiaoy312

Reputation: 14477

You can change it with a style. Just this under your Menu.Resources :

    <Style TargetType="MenuItem">
        <Setter Property="Background" Value="SkyBlue" />
    </Style>

EDIT: You can use AlternationCount to achieve this :

<Menu AlternationCount="2">
    <Menu.ItemContainerStyle>
        <Style TargetType="MenuItem">
            <Style.Triggers>
                <Trigger Property="ItemsControl.AlternationIndex" Value="0">
                    <Setter Property="Background"  Value="Red"></Setter>
                </Trigger>
                <Trigger Property="ItemsControl.AlternationIndex" Value="1">
                    <Setter Property="Background" Value="Blue"></Setter>
                </Trigger>
            </Style.Triggers>
        </Style>
    </Menu.ItemContainerStyle>

    <MenuItem Header="qwe" />
    <MenuItem Header="qwe" />
    <MenuItem Header="qwe" />
    <MenuItem Header="qwe" />
    <MenuItem Header="qwe" />
</Menu>

Upvotes: 5

Related Questions