Gib dem Command doch im Konstruktor die Daten mit, die es braucht?
Ist ja eine Klasse wie jede Andere auch
Oder, was auch gerne gemacht wird, streng genommen aber nicht ganz mit MVVM vereinbar ist, ist ein RelayCommand.
Also eine Klasse, die ICommand implementiert und für die Methoden eine Action<object> und eine Func<object, bool> im Konstruktor entgegen nimmt.
So kannst Du das im ViewModel "implementieren" und hast dann dort auch alle Daten, die es im ViewModel gibt - public und private
PS:
Hier gibt es eine Implementierung:
docs.telerik.com/dat...ase-and-relaycommand
Meine Eigene ist aber etwas komplexer, die nutze ich dann aber auch für jede weitere Command-Klasse:
1: 2: 3: 4: 5: 6: 7: 8: 9: 10: 11: 12: 13: 14: 15: 16: 17: 18: 19: 20: 21: 22: 23: 24: 25: 26: 27: 28: 29: 30: 31: 32: 33: 34: 35: 36: 37: 38: 39: 40: 41: 42: 43: 44: 45: 46: 47: 48: 49: 50: 51: 52: 53: 54: 55: 56:
| public class RelayCommand<TParameter> : ICommand { private readonly Action<TParameter> _execute; private readonly Func<TParameter, bool> _canExecute;
public event EventHandler CanExecuteChanged { add { CommandManager.RequerySuggested += value; } remove { CommandManager.RequerySuggested -= value; } }
public RelayCommand(Action<TParameter> execute, Func<TParameter, bool> canExecute = null) { if (execute == null) throw new ArgumentNullException(nameof(execute));
_execute = execute; _canExecute = canExecute ?? new Func<TParameter, bool>(_ => true); } protected RelayCommand() { }
public virtual void Execute(TParameter parameter) { _execute(parameter); } public virtual bool CanExecute(TParameter parameter) { return _canExecute(parameter); }
bool ICommand.CanExecute(object parameter) { return CanExecute((TParameter)parameter); } void ICommand.Execute(object parameter) { Execute((TParameter)parameter); } }
public class RelayCommand : RelayCommand<object> { public RelayCommand(Action execute, Func<bool> canExecute = null) : this(_ => execute(), canExecute == null ? null : new Func<object, bool>(_ => canExecute())) { } public RelayCommand(Action<object> execute, Func<object, bool> canExecute = null) : base(execute, canExecute) { } protected RelayCommand() { } } |
Die Nutzung sieht dann so aus:
C#-Quelltext
1: 2: 3: 4: 5: 6: 7: 8: 9: 10: 11:
| public class MyCommand : RelayCommand<int> { public override bool CanExecute(int parameter) { } public override void Execute(int parameter) { } } |
Du darfst dann natürlich nicht
base.CanExecute und
base.Execute aufrufen, das würde eine
NullReferenceException geben.
Oder die nicht ganz MVVM-Konforme Methode:
C#-Quelltext
1:
| public ICommand MyCommand { get; } |
C#-Quelltext
1:
| MyCommand = new RelayCommand<int>(() => , () => ); |