Search code examples
c#wpfmahapps.metro

WPF Menu Binding losing style only in the first level


Please let me know if I am doing something wrong in my code. I am trying to bind a WPF menu to a "MenuViewModel". The binding works as I expect in a non styled Window.

I am using MahApps.Metro for styling purposes only and this is how it looks after binding.

This is how it looks

Here's the link to the source code http://sdrv.ms/W5uJpY

ViewModel:

public class Menu : INotifyPropertyChanged
{
    public Menu()
    {
        IsEnabled = true;
        Children = new List<Menu>();
    }

    #region [ Menu Properties ]

    private bool _isEnabled;
    private string _menuText;
    private ICommand _command;
    private IList<Menu> _children;

    public string MenuText
    {
        get { return _menuText; }
        set
        {
            _menuText = value;
            RaisePropertyChanged("MenuText");
        }
    }

    public bool IsEnabled
    {
        get { return _isEnabled; }
        set
        {
            _isEnabled = value;
            RaisePropertyChanged("IsEnabled");
        }
    }

    public ICommand Command
    {
        get { return _command; }
        set
        {
            _command = value;
            RaisePropertyChanged("Command");
        }
    }

    public IList<Menu> Children
    {
        get { return _children; }
        set
        {
            _children = value;
        }
    }

    #endregion

    #region [INotifyPropertyChanged]
    public event PropertyChangedEventHandler PropertyChanged;

    protected virtual void RaisePropertyChanged(string propertyName)
    {
        if (PropertyChanged != null)
            PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
    }
    #endregion
}

XAML:

<Menu Grid.Row ="0" IsMainMenu="True" x:Name="mainMenu" VerticalAlignment="Top" ItemsSource="{Binding Children}">
    <Menu.ItemContainerStyle>
        <Style TargetType="{x:Type MenuItem}" BasedOn="{StaticResource {x:Type MenuItem}}">
        <!--Or can be the line below, both yield the same result-->
        <!--<Style TargetType="{x:Type MenuItem}" BasedOn="{StaticResource MetroMenuItem}">-->
        <!--NOTICE THAT SUB MENU's of OPEN work fine-->
            <Setter Property="Header" Value="{Binding Path=MenuText}"/>
            <Setter Property="Command" Value="{Binding Path=Command}"/>
            <Setter Property="ItemsSource" Value="{Binding Path=Children}"/>
        </Style>
    </Menu.ItemContainerStyle>
</Menu>

Solution

  • I think I found an answer here

    http://karlshifflett.wordpress.com/2008/02/03/wpf-sample-series-databound-hierarchicaldatatemplate-menu-sample/

    It does the binding correctly - along with maintaining Separators.