您可以使用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;
}
}
不要忘記分配的MainWindow
DataContext
:
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
}
試圖理解你的問題 - 爲什麼RibbonCommand被刪除? – RQDQ
@RQDQ它改變了,現在RibbonCommand不存在 –