1

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

任何帮助将不胜感激,

4

1 回答 1

1
 <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}" 
                  Visibility="{Binding DataContext.RemoveVisibility,RelativeSource={RelativeSource AncestorType={x:Type TreeView}}}"
                  />

private Visibility _removeVisibility;

    public Visibility RemoveVisibility
    {
        get { return _removeVisibility; }
        set { _removeVisibility = value; Notify("RemoveVisibility"); }
    }

    public bool CanRemoveAll(object param)
    {
        GoldTreeNodeViewModel gtn = param as GoldTreeNodeViewModel;
        bool result= (gtn != null && gtn.Children != null && gtn.Children.Count > 0);
        if (result)
            RemoveVisibility = Visibility.Visible;
        else
            RemoveVisibility = Visibility.Collapsed;
        return result;
    }

我认为您绑定的 DataContext 对应于您的 ViewModel 。我希望这将有所帮助。

于 2013-02-10T13:34:02.433 回答