2013-02-10 63 views
1

我使用的约什 - 史密斯RelayCommand类在WPF MVVM应用程序为我的ViewModel里面创建我的命令结合RelayCommand CanExecute:菜单项可视性与参数

例如:

ICommand RemoveAllCommand = new RelayCommand<object>(OnRemoveAll, CanRemoveAll); 

我打电话这从文本菜单命令:

<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}" /> 

一切正常,只是我的菜单项的仍然是可见的,但残疾人,我想设置的知名度,所以晕倒第在继电器命令中的CanExecute返回false时,我的MenuItem不显示。

我试图设置一个绑定到Visibility属性,但我不知道如何绑定到我的CanRemoveAll(object obj)方法的参数。我也想过使用DataTrigger,但我不知道如何去做。

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

任何帮助将高度赞赏,

+0

您能否在VM中显示CanRemoveAll的代码,以及您从哪里提出CanExecuteChanged。 – ethicallogics 2013-02-10 13:03:18

+0

只需将该信息添加到问题中。此外,我并不是在任何地方显式提高CanExecuteChanged,我认为'RelayCommand'和WPF内部负责就我所知。 – 2013-02-10 13:24:58

回答

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。我希望这将有所帮助。

+0

哦,这很有意义,虽然我可能需要使用我的布尔可见性转换器,但这是次要的。让我试试看,并感谢您的建议 – 2013-02-10 13:40:45

+0

是的,你可以做到这一点,并创建转换器将bool转换为可见性。 – ethicallogics 2013-02-10 13:42:12

+0

虽然我不确定在虚拟机中创建Visibility类型属性,但听起来更像View相关的,但我可以创建一个'public bool IsRemoveAllVisible'属性... – 2013-02-10 13:43:43