2013-02-10 49 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