ViewModel 内でコマンドを作成するために、WPF MVVM アプリで Josh Smith RelayCommand クラスを使用しています。
例えば:
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}" />
CanExecute
私のMenuItemがまだ表示されているが無効になっていることを除いて、すべて正常に動作します。リレーコマンドがfalseを返したときにMenuItemが表示されないように、VisibilityをCollapsedに設定したいと思います。
CanRemoveAll(object obj)
Visibility プロパティへのバインドを設定しようとしましたが、パラメーターを使用してメソッドにバインドする方法がわかりません。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);
}
どんな助けでも大歓迎です、