我就是这样解决的
我创建了一个 MenuItem 类(请注意,它有一个项目列表,因此您可以构建子菜单):
public class MenuItem : ModelBase<MenuItem>
{
private List<MenuItem> _Items;
public MenuItem(string header, ICommand command)
{
Header = header;
Command = command;
}
public MenuItem()
{
}
public string Header { get; set; }
public List<IMenuItem> Items
{
get { return _Items ?? (_Items = new List<IMenuItem>()); }
set { _Items = value; }
}
public ICommand Command { get; set; }
public string CommandName { get; set; }
public object Icon { get; set; }
public bool IsCheckable { get; set; }
private bool _IsChecked;
public bool IsChecked
{
get { return _IsChecked; }
set
{
_IsChecked = value;
NotifyPropertyChanged(m=>m.IsChecked);
}
}
public bool Visible { get; set; }
public bool IsSeparator { get; set; }
public string InputGestureText { get; set; }
public string ToolTip { get; set; }
public int MenuHierarchyID { get; set; }
public int ParentMenuHierarchyID { get; set; }
public string IconPath { get; set; }
public bool IsAdminOnly { get; set; }
public object Context { get; set; }
public IMenuItem Parent { get; set; }
public int int_Sequence { get; set; }
public int int_KeyIndex { get; set; }
}
和一个视图:
<Menu DockPanel.Dock="Top" ItemsSource="{Binding Path=MainMenu}">
<Menu.ItemContainerStyle>
<Style>
<Setter Property="MenuItem.Header" Value="{Binding Path=Header}" />
<Setter Property="MenuItem.ItemsSource" Value="{Binding Path=Items}" />
<Setter Property="MenuItem.Icon" Value="{Binding Path=Icon}" />
<Setter Property="MenuItem.IsCheckable" Value="{Binding Path=IsCheckable}" />
<Setter Property="MenuItem.IsChecked" Value="{Binding Path=IsChecked,Mode=TwoWay,UpdateSourceTrigger=PropertyChanged}" />
<Setter Property="MenuItem.Command" Value="{Binding Path=Command}" />
<!--<Setter Property="MenuItem.CommandParameter" Value="{Binding Path=IsChecked}"/>-->
<Setter Property="MenuItem.CommandParameter" Value="{Binding Path=.}"/>
<Setter Property="MenuItem.InputGestureText" Value="{Binding Path=InputGestureText}"/>
<Setter Property="MenuItem.ToolTip" Value="{Binding Path=ToolTip}" />
<Style.Triggers>
<DataTrigger Binding="{Binding Path=IsSeparator}" Value="true">
<Setter Property="MenuItem.Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type MenuItem}">
<Separator Style="{DynamicResource {x:Static MenuItem.SeparatorStyleKey}}" />
</ControlTemplate>
</Setter.Value>
</Setter>
</DataTrigger>
</Style.Triggers>
</Style>
</Menu.ItemContainerStyle>
</Menu>
MainMenu
我的主 ViewModel中的属性在哪里ObservableCollection
,您可以从数据库中填充该属性。
public ObservableCollection<MenuItem> MainMenu
{
get { return _MainMenu; }
set
{
_MainMenu = value;
NotifyPropertyChanged(x => x.MainMenu);
}
}