问题描述
|
我正在尝试使用MVVM模式在窗口中实现菜单。因此,我创建了一个MainWindow并将其绑定到MainWindowviewmodel。 MainWindowviewmodel包含MainWindowMenuviewmodel,它是专门为Menu设计的VM。它是MenuItemviewmodels的层次结构。
一切似乎都很简单,但是我有一个问题-运行应用程序时菜单显示不正确-似乎没有设置Header属性。菜单位于左上角,但未显示任何文本。我可以单击它并将其打开,但是所有MenuItems均为空白。奇怪的是:绑定的ICommands起作用了!但是没有显示标题。
这是我的资源
<Style x:Key=\"MenuItemStyle\" targettype=\"{x:Type MenuItem}\" >
<Style.Setters>
<Setter Property=\"Header\" Value=\"{Binding Path=Title}\" />
<Setter Property=\"Command\" Value=\"{Binding Path=Command}\" />
</Style.Setters>
</Style>
<HierarchicalDataTemplate
x:Key=\"MenuDataTemplate\"
DataType=\"{x:Type vw:MenuItemviewmodel}\"
ItemsSource=\"{Binding Path=SubMenuItems}\"
ItemContainerStyle=\"{StaticResource ResourceKey=MenuItemStyle}\"
>
</HierarchicalDataTemplate>
MainWindow.xaml包含菜单:
<DockPanel>
<Menu
DockPanel.Dock=\"Top\"
ItemsSource=\"{Binding Path=Menu.MenuItems}\"
ItemTemplate=\"{StaticResource ResourceKey=MenuDataTemplate}\"
/>
</DockPanel>
MenuItemView是:
using System.Collections.Generic;
using System.Windows.Input;
namespace WpfMvvmMenu.viewmodel
{
public class MenuItemviewmodel
{
public MenuItemviewmodel(string title,ICommand command)
{
this.Title = title;
this.Command = command;
this.SubMenuItems = new List<MenuItemviewmodel>();
}
public string Title { get; private set; }
public ICommand Command { get; private set; }
public IList<MenuItemviewmodel> SubMenuItems { get; private set; }
}
}
我在这里看到了所有的MVVM-Menu文章,但是他们都说我的DataTemplate可以,因此必须有其他内容。
谢谢。
解决方法
我认为,当您使用ѭ3you时,即使将模板
MenuItem
的Content
保留为空,也可以将其设置为模板的内容。此代码有效:
<Style x:Key=\"MenuItemStyle\" TargetType=\"{x:Type MenuItem}\">
<Style.Setters>
<Setter Property=\"Command\" Value=\"{Binding Path=Command}\" />
</Style.Setters>
</Style>
<HierarchicalDataTemplate
x:Key=\"MenuDataTemplate\"
DataType=\"{x:Type vw:MenuItemViewModel}\"
ItemsSource=\"{Binding Path=SubMenuItems}\"
ItemContainerStyle=\"{StaticResource MenuItemStyle}\"
>
<ContentPresenter Content=\"{Binding Title}\" />
</HierarchicalDataTemplate>
另一方面,您根本不需要模板。您可以使用以下样式直接在菜单上设置ItemContainerStyle=\"{StaticResource MenuItemStyle}\"
:
<Style x:Key=\"MenuItemStyle\" TargetType=\"{x:Type MenuItem}\">
<Style.Setters>
<Setter Property=\"Header\" Value=\"{Binding Path=Title}\" />
<Setter Property=\"Command\" Value=\"{Binding Path=Command}\" />
<Setter Property=\"ItemsSource\" Value=\"{Binding SubMenuItems}\" />
</Style.Setters>
</Style>