0

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

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

这是它的样子

这是源代码的链接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>
4

1 回答 1

0

我想我在这里找到了答案

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

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

于 2012-12-28T19:39:31.203 回答