wpf 如何在上下文菜单中获取所选项目

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11741397/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-13 04:47:02  来源:igfitidea点击:

How to get the Selected Item in Context Menu

wpf

提问by Leah Smith

I have a context menu that has binding items and I want to set up a command and command parameter so I know which item was clicked on but I don't know how.

我有一个包含绑定项目的上下文菜单,我想设置一个命令和命令参数,这样我就知道点击了哪个项目,但我不知道如何点击。

<MenuItem Command="{Binding Sync}"   
  Header="Synchronize" 
  ItemsSource="{Binding ItemsToSync}">
  <MenuItem.Icon>
      <Image Height="25" Source="Sync.png" />
  </MenuItem.Icon>
</MenuItem>

回答by TMan

You can try something like this: In this example I have a listview and I can right click and delete a selected item. The Reason I'm using RelativeSource here is because when it comes to passing parameters in menuitems, most of the time at this level you can't reach the datacontext of the page. Hope this helps.

你可以尝试这样的事情:在这个例子中,我有一个列表视图,我可以右键单击并删除选定的项目。我在这里使用RelativeSource 的原因是因为当涉及到在菜单项中传递参数时,大部分时间在这个级别您无法访问页面的数据上下文。希望这可以帮助。

               <ListView.ContextMenu>
                    <ContextMenu>
                        <MenuItem Header="Delete" Command="{Binding Path=DeleteDescriptions}" CommandParameter="{Binding RelativeSource={RelativeSource AncestorType=ContextMenu}, Path=PlacementTarget.SelectedItem}" Name="MenuItem1">
                        </MenuItem>
                    </ContextMenu>
                </ListView.ContextMenu>

回答by Leah Smith

That did not help but I was able to create my own solution.

这没有帮助,但我能够创建自己的解决方案。

 <MenuItem Header="Synchronize" ItemsSource="{Binding ItemsToSync}">
                    <MenuItem.Icon>
                        <Image Height="25" Source="Sync.png" />
                    </MenuItem.Icon>
                    <MenuItem.ItemContainerStyle>
                        <Style>
                            <Setter Property="MenuItem.Header" Value="{Binding Name}" />
                            <Setter Property="MenuItem.IsChecked" Value="{Binding IsCurrent}" />
                            <Setter Property="MenuItem.Command" Value="PT:Commands.SyncFromContextMenu" />
                            <Setter Property="MenuItem.CommandParameter" Value="{Binding}" />
                        </Style>
                    </MenuItem.ItemContainerStyle>

                </MenuItem>
</MenuItem>

I did have to create a static class for the command.

我确实必须为命令创建一个静态类。