将项目绑定到 MenuItem ->使用命令
- 作者: 闹够了没有wait
- 来源: 51数据库
- 2022-10-20
问题描述
我有一个 MenuItem,其中包含一组项目.它看起来像文件 -> 打开菜单项.
I have a MenuItem, which has a collection of items in it. It looks like the File -> Open Menuitem.
所以:
- 文件
- 打开
- 从数据库打开
- 文件 1
- 文件 2
- 文件 3
XAML 代码:
<Menu> <MenuItem Header="File"> <MenuItem Header="Open"> <MenuItem Header="From Database" ItemsSource="{Binding OCFragebogen}"/> </MenuItem> </MenuItem> </Menu>我想在单击特定项目时调用命令.示例:用户单击文件 1,应调用命令,其中文件 1"是命令参数.
I want to call a Command, when a specific item has been clicked. Example: User clicks on File 1, a command should be called where the "File 1" is the Command Parameter.
ViewModel 包含我想在 MenuItem集合"中显示的项目
ViewModel contains the Items, which I want to display in the MenuItem "collection"
private ObservableCollection<string> _OCFragebogen; public ObservableCollection<string> OCFragebogen { get { if (_OCFragebogen == null) _OCFragebogen = new ObservableCollection<string>(); return _OCFragebogen; } set { _OCFragebogen = value; RaisePropertyChanged(() => OCFragebogen); } }明确地说:当用户点击 MenuItem 中的一个项目(来自 ItemsSource)时,应该调用一个命令,我想对点击的项目执行某些操作.
To make it clear: When the user clicks on an item (from the ItemsSource) in the MenuItem, a Command should be called where I want to do something with the clicked Item.
我必须在哪里使用命令来调用 ViewModel 中的方法 (RelayCommand)?我希望在单击 ItemsSource 中的一个项目时使用它 + 我想将单击的项目传递给该方法.
Where do I have to use the command to call a method (RelayCommand) in my ViewModel? I want it to be used when an Item from the ItemsSource has been clicked + I want to pass the clicked item to the method.
推荐答案
这应该对你有用
<MenuItem Header="From Database" ItemsSource="{Binding YourItemSource}"> <MenuItem.ItemContainerStyle> <Style TargetType="MenuItem"> <Setter Property="Command" Value="{Binding RelativeSource={RelativeSource Mode=FindAncestor, AncestorType=MenuItem}, Path=DataContext.YourCommandName}"></Setter> <Setter Property="CommandParameter" Value="{Binding}"></Setter> </Style> </MenuItem.ItemContainerStyle> </MenuItem>
- 从数据库打开
- 打开
- C#通过fleck实现wss协议的WebSocket多人Web实时聊天(附源码)
- 团队城市未满足要求:MSBuildTools12.0_x86_Path 存在
- 使用 MSBuild.exe 在发布模式下构建 C# 解决方案
- 当我发布 Web 应用程序时,AfterPublish 脚本不运行
- 构建时 T4 转换的产品仅在下一个构建中使用
- ASP.NET Core Application (.NET Framework) for Windows x64 only error in project.assets.json
- 新的 .csproj 格式 - 如何将整个目录指定为“链接文件"到子目录?
- 如何将条件编译符号(DefineConstants)传递给 msbuild
- MSBuild 支持 Visual Studio 2017 RTM 中的 T4 模板
- NuGet 包还原找不到包,没有源
