动态绑定到Window的MenuItem上的ViewModel命令

Pie*_*ler 5 wpf command datatemplate mvvm menuitem

使用MVVM结构处理WPF应用程序.

我的窗口显示一个菜单和当前的ViewModel.在Menu的MenuItem之一上,我想列出当前ViewModel中的一些命令.菜单中列出的命令将根据ViewModel而改变.

我得到了这个工作得很好,但风格搞砸了 - Command MenuItems在另一个菜单框或其他内容.我会附上截图.

我在ViewViewModel中包装了ViewModel的ICommand对象(在本例中为RelayCommands),它在菜单上公开了我想要的Command和Display字符串.这些CommandViewModel位于列表中:CurrentWorkspace.AdditionalOptionsCommands.

这是菜单的XAML.就像我说的那样,它起作用,它显示正确的项目并执行命令.显示是不正确的 - 任何人都可以告诉我为什么以及如何解决它?查看截图.

<Menu>
    <MenuItem Header="_Additional Options..." ItemsSource="{Binding Path=CurrentWorkspace.AdditionalOptionsCommands}">
        <MenuItem.ItemTemplate>
            <DataTemplate DataType="{x:Type vm:CommandViewModel}">
                <MenuItem Header="{Binding Path=DisplayText}" Command="{Binding Path=Command}"/>
            </DataTemplate>
        </MenuItem.ItemTemplate>
    </MenuItem>
    <MenuItem Header="_Testing">
        <MenuItem Header="This looks right" />
        <MenuItem Header="This looks right" />
    </MenuItem>   
</Menu>  
Run Code Online (Sandbox Code Playgroud)

目前的外观:

目前的外观

期望的外观:

期望的外观

Pav*_*kov 8

这是因为当您通过ItemsSource每个项目指定菜单项时会自动将其包装到一个MenuItem对象中.这样,DataTemplate(MenuItem元素)中定义的内容将被包装成一个MenuItem.

您需要做什么而不是定义a DataTemplate是为MenuItem您设置绑定到视图模型属性的位置定义样式,ItemContainerStyle并在父项上使用此样式MenuItem:

<Window.Resources>
    <Style x:Key="CommandMenuItemStyle"
           TargetType="{x:Type MenuItem}">
         <Setter Property="Header"
                 Value="{Binding Path=DisplayText}"/> 
         <Setter Property="Command"
                 Value="{Binding Path=Command}"/>
    </Style>
</Window.Resources>
...
<Menu>
    <MenuItem Header="_Additional Options..." 
              ItemsSource="{Binding Path=CurrentWorkspace.AdditionalOptionsCommands}" 
              ItemContainerStyle="{StaticResource CommandMenuItemStyle}"/>
    <MenuItem Header="_Testing">
        <MenuItem Header="This looks right" />
        <MenuItem Header="This looks right" />
    </MenuItem>   
</Menu>   
Run Code Online (Sandbox Code Playgroud)

有关项容器如何使用控件的深入说明,请参见http://drwpf.com/blog/2008/03/25/itemscontrol-i-is-for-item-container/ItemsControl.