2

この古いコードをRibbonApplicationMenuItemに置き換える方法の例を探しています。質問は、削除されたRibbonCommandを置き換える方法です

<ResourceDictionary>
   <r:RibbonCommand 
     x:Key="MenuItem1" 
     CanExecute="RibbonCommand_CanExecute" 
     LabelTitle="Menu Item 1" 
     LabelDescription="This is a sample menu item" 
     ToolTipTitle="Menu Item 1" 
     ToolTipDescription="This is a sample menu item" 
     SmallImageSource="Images\files.png" 
     LargeImageSource="Images\files.png" />
  </ResourceDictionary>
</r:RibbonWindow.Resources>

<r:RibbonApplicationMenuItem Command="{StaticResource MenuItem1}">
</r:RibbonApplicationMenuItem>
4

1 に答える 1

3

を使用できますRelayCommand

この場合のバインドは非常に簡単です。

<ribbon:RibbonApplicationMenuItem Header="Hello _Ribbon"
                              x:Name="MenuItem1"
                              ImageSource="Images\LargeIcon.png"
                              Command="{Binding MyCommand}"
                              />

この場合のViewModelクラスには、次MyCommandICommandタイプのプロパティが含まれている必要があります。

public class MainViewModel
{   
    RelayCommand _myCommand;
    public ICommand MyCommand
    {
        get
        {
            if (_myCommand == null)
            {
                _myCommand = new RelayCommand(p => this.DoMyCommand(p),
                    p => this.CanDoMyCommand(p));
            }
            return _myCommand;
        }
    }

    private bool CanDoMyCommand(object p)
    {
        return true;
    }

    private object DoMyCommand(object p)
    {
        MessageBox.Show("MyCommand...");
        return null;
    }
}

DataContextの割り当てを忘れないでくださいMainWindow

public MainWindow()
{
    InitializeComponent();
    this.DataContext = new MainViewModel();
}

RelayCommandクラス:

public class RelayCommand : ICommand
{
    #region Fields

    readonly Action<object> _execute;
    readonly Predicate<object> _canExecute;

    #endregion // Fields

    #region Constructors

    public RelayCommand(Action<object> execute)
        : this(execute, null)
    {
    }

    public RelayCommand(Action<object> execute, Predicate<object> canExecute)
    {
        if (execute == null)
            throw new ArgumentNullException("execute");

        _execute = execute;
        _canExecute = canExecute;
    }
    #endregion // Constructors

    #region ICommand Members

    public bool CanExecute(object parameter)
    {
        return _canExecute == null ? true : _canExecute(parameter);
    }

    public event EventHandler CanExecuteChanged
    {
        add { CommandManager.RequerySuggested += value; }
        remove { CommandManager.RequerySuggested -= value; }
    }

    public void Execute(object parameter)
    {
        _execute(parameter);
    }

    #endregion // ICommand Members
}
于 2013-01-22T17:22:58.170 に答える