WPF:添加命令以通过绑定菜单项自动生成

时间:2012-12-31 07:29:01

标签: wpf mvvm binding command

使用MVVM。我创建了单独的菜单'Recent files',它从绑定中获取其项目。它看起来像是:

enter image description here

        <MenuItem Header="_Recent files" ItemsSource="{Binding RecentFiles, Converter={StaticResource RecentFilesToListOfStringsConverter}, Mode=OneWay}" >
        </MenuItem>

现在,我想为每个自动生成的项添加Command,它应该将路径作为命令参数并通过单击执行导入文件操作。

您能否建议如何以MVVM方式完成?

1 个答案:

答案 0 :(得分:20)

再一次,我自己找到了解决方案。我试图像下面那样以错误的方式放置命令,但它不起作用:

            <MenuItem Header="_Recent files" ItemsSource="{Binding RecentFiles, Converter={StaticResource RecentFilesToListOfStringsConverter}, Mode=OneWay}" >
            <MenuItem.ItemContainerStyle>
                <Style TargetType="{x:Type MenuItem}">
                    <Setter Property="Command" Value="{Binding ImportRecentItemCommand}" />
                </Style>
            </MenuItem.ItemContainerStyle>
        </MenuItem>

这是正确的方法。还是不明白它是如何工作的,必须深入学习WPF!

            <MenuItem Header="_Recent files" ItemsSource="{Binding RecentFiles, Converter={StaticResource RecentFilesToListOfStringsConverter}, Mode=OneWay}" >
            <MenuItem.ItemContainerStyle>
                <Style TargetType="{x:Type MenuItem}">
                    <Setter Property="Command" Value="{Binding DataContext.ImportRecentItemCommand, RelativeSource={RelativeSource Mode=FindAncestor, AncestorType={x:Type MenuItem}, AncestorLevel=1}}" />
                </Style>
            </MenuItem.ItemContainerStyle>
        </MenuItem>

编辑:最终版

XAML:

            <MenuItem Header="_Recent files" ItemsSource="{Binding RecentFiles, Converter={StaticResource RecentFilesToListOfStringsConverter}, Mode=OneWay}" >
            <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>
        </MenuItem>

ViewModel:使用MVVM Light Toolkit,RelayCommand从那里开始:

        private ICommand _importRecentItemCommand;

        public ICommand ImportRecentItemCommand
        {
            get { return _importRecentItemCommand ?? (_importRecentItemCommand = new RelayCommand<object>(ImportRecentItemCommandExecuted)); }
        }

        private void ImportRecentItemCommandExecuted(object parameter)
        {
            MessageBox.Show(parameter.ToString());
        }

享受