1

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 の使用も考えましたが、その方法がわかりません。

CanRemoveAllViewModel での私のメソッドは次のとおりです。

    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 に答える