2013-01-22 93 views
2

我正在尋找一個示例如何替換RibbonApplicationMenuItem的舊代碼。問題是如何替換刪除RibbonCommandWPF Ribbon RibbonCommand替換爲ICommand

<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> 
+0

試圖理解你的問題 - 爲什麼RibbonCommand被刪除? – RQDQ

+0

@RQDQ它改變了,現在RibbonCommand不存在 –

回答

2

您可以使用RelayCommand

在這種情況下,綁定是非常簡單的:

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

在這種情況下,你的ViewModel類,必須包含ICommand類型的財產MyCommand

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

不要忘記分配的MainWindowDataContext

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

RelayCommand class:

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 
} 
+0

@kmatyazek thanx你這個用法很好的例子。好工作 –