绑定项目以菜单项 - >使用命令 [英] Bind Items to MenuItem -> use Command

查看:171
本文介绍了绑定项目以菜单项 - >使用命令的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个菜单项,其具有在它的项目的集合。它看起来像文件 - >打开菜单项

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 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);
            }
        }
        



        为了明确这一点:当一个用户点击。项目(从的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.

        编辑:我在哪里必须使用命令来调用我的视图模型的方法(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>
        

        这篇关于绑定项目以菜单项 - &GT;使用命令的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆