我正在尝试使用 MVVM 模式在窗口中实现菜单。所以我创建了一个 MainWindow 并将其绑定(bind)到 MainWindowViewModel。 MainWindowViewModel 包含 MainWindowMenuViewModel,它是一个专门为 Menu 设计的 VM。它是 MenuItemViewModels 的层次结构。
一切似乎都很简单,但我有一个问题——当我运行应用程序时,菜单没有正确呈现——似乎没有设置 Header 属性。菜单位于左上角,但没有显示任何文本。我可以单击它并打开它,但所有 MenuItems 都是空白的。奇怪的是:绑定(bind)的 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 还可以,所以肯定还有别的东西。
谢谢你。
最佳答案
我认为当您使用 HierarchicalDataTemplate
, 你设置 Content
的模板 MenuItem
模板的内容,即使您将其留空。此代码有效:
<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>
关于wpf - 使用 MVVM 绑定(bind) WPF 菜单 - 查找错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6397858/