I'd like to change the background color of a MenuItem in WPF if the page it links to is the page I'm currently on. I've already figured out how to change a MenuItem upon MouseOver, and figured it would be a similar process for an active page. Unfortunately all the links I've seen here when searching for this problem solve the issue for MouseOver, not for the active page.
I was thinking along the lines of setting the "IsFocused" trigger in the code-behind, but that doesn't seem to work because IsFocused is readonly, and I'm not sure if that's the correct property to set anyways.
<StackPanel Name="spMainNav">
<StackPanel.Resources>
<ControlTemplate x:Key="VsMenuSub" TargetType="MenuItem">
<StackPanel>
<Label Content="{TemplateBinding Header}" Foreground="White" />
<StackPanel.Style>
<Style TargetType="StackPanel">
<Style.Triggers>
<Trigger Property="IsMouseOver" Value="True">
<Setter Property="Background" Value="Red" />
</Trigger>
<!--Don't know where to set this in code-behind?-->
<Trigger Property="IsFocused" Value="True">
<Setter Property="Background" Value="DarkRed" />
</Trigger>
</Style.Triggers>
</Style>
</StackPanel.Style>
</StackPanel>
</ControlTemplate>
</StackPanel.Resources>
<MenuItem Name="ProjectList" Header="Project List" Template="{StaticResource VsMenuSub}" Click="ProjectList_Click" />
<MenuItem Header="About" Template="{StaticResource VsMenuSub}" Click="About_Click" />
<MenuItem Header="Exit" Template="{StaticResource VsMenuSub}" Click="Exit_Click" />
</StackPanel>
I'm able to modify the header text of an active link (appending two asterisks to the beginning). I thought I could set the background color this way, but I can't figure out how to do it. Setting the Background field of the MenuItem to a brush doesn't work.
Public Shared Sub HighlightMenuItem(sender As MenuItem)
Dim sp As StackPanel = sender.Parent
Dim bc As New BrushConverter
sp.Background = bc.ConvertFrom("#36637C")
Dim thisMI As MenuItem = sender
Dim controlCount As Integer = VisualTreeHelper.GetChildrenCount(sp)
For i As Integer = 0 To controlCount - 1
Dim c = VisualTreeHelper.GetChild(sp, i)
If TypeOf c Is MenuItem Then
Dim mi As MenuItem = c
If mi.Header = thisMI.Header Then
mi.Header = "** " & mi.Header
' This doesn't work
mi.Background = Brushes.Blue
End If
End If
Next
End Sub