MenuItem可见性绑定到RelayCommand CanExecute with Parameter

时间:2013-02-10 12:41:19

标签: wpf contextmenu relaycommand

我在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仍然可见但已禁用,我想将可见性设置为折叠,以便当Relay Command中的CanExecute返回false时,我的MenuItem不会显示。

我尝试设置绑定到Visibility属性,但我不知道如何使用参数绑定到我的CanRemoveAll(object obj)方法。我还考虑过使用DataTrigger,但我不知道该怎么做。

以下是ViewModel中的CanRemoveAll方法:

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

任何帮助都将受到高度赞赏,

1 个答案:

答案 0 :(得分: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。我希望这会有所帮助。