且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

从MVVM中的视图模型绑定命令到WPF菜单

更新时间:2022-10-21 12:47:25


它应该绑定如下所示。

< MenuItem.ItemContainerStyle> 
< Style TargetType =" {x:Type MenuItem}">
< Setter Property =" Command" Value =" {Binding DataContext.ImportRecentItemCommand,RelativeSource = {RelativeSource Mode = FindAncestor,AncestorType = {x:Type MenuItem},AncestorLevel = 1}}" /&GT;
< Setter Property =" CommandParameter"值= QUOT; {结合}&QUOT; /&GT;
< / Style>
< /MenuItem.ItemContainerStyle>

WPF - 如何使用绑定创建菜单和子菜单


***的问候,


鲍勃


Hi Guys,

I have one command object and i have to bind all menu items to same command object. I use the command parameter to differentiate between different menu items.

How can i bind the Command object to dynamically generated menu item in view model?

What i have tried:

1. I tried to set Command Object of menu directly in ViewModel.

2. I tried to use SetBinding to set the command.

But none of these solutions are working.


Veeresh Angadi

Hi,

It should bind as below.

         <MenuItem.ItemContainerStyle>
                <Style TargetType="{x:Type MenuItem}">
                    <Setter Property="Command" Value="{Binding DataContext.ImportRecentItemCommand, RelativeSource={RelativeSource Mode=FindAncestor, AncestorType={x:Type MenuItem}, AncestorLevel=1}}" />
                    <Setter Property="CommandParameter" Value="{Binding}" />
                </Style>
            </MenuItem.ItemContainerStyle>

WPF - How can I create menu and submenus using binding

Best Regards,

Bob