WPF菜单仅在第一级绑定丢失样式

时间:2012-12-28 14:16:54

标签: c# wpf mahapps.metro

如果我在代码中出错了,请告诉我。我试图将WPF菜单绑定到“MenuViewModel”。绑定按照我在非样式窗口中的预期工作。

我使用MahApps.Metro仅用于样式目的,这就是它在绑定后的样子。

This is how it looks http://i45.tinypic.com/2n74but.png

以下是源代码http://sdrv.ms/W5uJpY

的链接

视图模型:

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>

1 个答案:

答案 0 :(得分:0)

我想我在这里找到了答案

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

它正确地进行绑定 - 以及维护分隔符。