我在 WPF MVVM 应用程序中使用 Josh Smith RelayCommand 类在 ViewModel 中创建命令:
例如:
ICommand RemoveAllCommand = new RelayCommand<object>(OnRemoveAll, CanRemoveAll);
我从 ContextMenu 调用这个命令:
<ContextMenu x:Key="MyContextMenu" DataContext="{Binding Path=PlacementTarget, RelativeSource={RelativeSource Self}}">
    <MenuItem Header="Remove All" Command="{Binding Path=DataContext.RemoveAllCommand,
                                  RelativeSource={RelativeSource AncestorType={x:Type TreeView}}}" CommandParameter="{Binding Path=.Header}" />
一切正常,除了我的 MenuItem 仍然可见但被禁用,我想将 Visibility 设置为 Collapsed 以便CanExecute在 Relay Command 返回 false 时我的 MenuItem 不会显示。
我尝试设置与 Visibility 属性的绑定,但我不知道如何CanRemoveAll(object obj)使用参数绑定到我的方法。我也考虑过使用 DataTrigger,但我不知道该怎么做。
这是我CanRemoveAll在 ViewModel 中的方法:
    public bool CanRemoveAll(object param)
    {
        GoldTreeNodeViewModel gtn = param as GoldTreeNodeViewModel;
        return (gtn != null && gtn.Children != null && gtn.Children.Count > 0);
    }
从 RelayCommand 类:
public event EventHandler CanExecuteChanged
    {
        add
        {
            if (_canExecute != null)
                CommandManager.RequerySuggested += value;
        }
        remove
        {
            if (_canExecute != null)
                CommandManager.RequerySuggested -= value;
        }
    }
    [DebuggerStepThrough]
    public Boolean CanExecute(Object parameter)
    {
        return _canExecute == null ? true : _canExecute((T) parameter);
    }
任何帮助将不胜感激,