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 类必须包含MyCommand以下ICommand类型的属性:

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;
    }
}

不要忘记分配DataContextMainWindow

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 回答